html 구성 요소 템플릿에 로컬 변수로 데이터를 공유하기 위한 Angular 구조 지시문

8572 단어 angular
때로는 데이터를 로컬 변수로 구성 요소 템플릿에 공유해야 할 필요가 있습니다. 이 구조 지시어는 html 템플릿에 사용할 수 있는 변수의 로컬 컨텍스트를 생성합니다.

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

interface NgLetContext<T> {
    ngLet: T;
    $implicit: T;
}

@Directive({
    // tslint:disable-next-line: directive-selector
    selector: '[ngLet]'
})
export class NgLetDirective<T> {

    private context: NgLetContext<T | null> = { ngLet: null, $implicit: null };
    private hasView: boolean = false;

    // eslint-disable-next-line no-unused-vars
    constructor(private viewContainer: ViewContainerRef, private templateRef: TemplateRef<NgLetContext<T>>) { }

    @Input()
    set ngLet(value: T) {
        this.context.$implicit = this.context.ngLet = value;
        if (!this.hasView) {
            this.viewContainer.createEmbeddedView(this.templateRef, this.context);
            this.hasView = true;
        }
    }

    /** @internal */
    public static ngLetUseIfTypeGuard: void;

    /**
     * Assert the correct type of the expression bound to the `NgLet` input within the template.
     *
     * The presence of this static field is a signal to the Ivy template type check compiler that
     * when the `NgLet` structural directive renders its template, the type of the expression bound
     * to `NgLet` should be narrowed in some way. For `NgLet`, the binding expression itself is used to
     * narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgLet`.
     */
    static ngTemplateGuard_ngLet: 'binding';

    /**
     * Asserts the correct type of the context for the template that `NgLet` will render.
     *
     * The presence of this method is a signal to the Ivy template type-check compiler that the
     * `NgLet` structural directive renders its template with a specific context type.
     */
    static ngTemplateContextGuard<T>(dir: NgLetDirective<T>, ctx: any): ctx is NgLetContext<Exclude<T, false | 0 | '' | null | undefined>> {
        return true;
    }
}


용법

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <ng-container *ngLet="(num1 + num2) as total"> <!-- single computation -->
    <div>
      1: {{ total }} <!-- 3 -->
    </div>
    <div>
      2: {{ total }} <!-- 3 -->
    </div>
  </ng-container> 
  `,
})
export class AppComponent {
  num1: number = 1;
  num2: number = 2;
}


이 트릭은 npm 라이브러리https://www.npmjs.com/package/ng-let로도 게시됩니다.

좋은 웹페이지 즐겨찾기