영웅처럼 Angular에서 사용자 지정 구조 지시문 빌드하기 😎

소개



Angular는 몇 가지 기본 제공 지시문과 함께 제공됩니다.

Structural Directive는 DOM에서 HTML 구조를 조작하는 데 사용할 수 있습니다. 이를 사용하여 DOM 일부의 구조를 변경할 수 있습니다.
  • *ngIf
  • *ngForOf
  • *ngSwitch

  • 사용자 정의 구조 지시문 만들기



    사용자 지정 구조 지시문이 필요한 이유는 무엇입니까?

    We have build in structural directive that satisfies our solution, what if we might come across a case that the ones provided with the framework don't solve. so here comes the custom structural directive.



    따라서 이 문서에서는 *ngIf 구조 지시문을 복제해 보겠습니다.
    *ngIf 구조 지시문을 생성하는 방법을 이해해 보겠습니다.

    Angular CLI를 사용하여 프로젝트를 만들어 봅시다




    // use this command to create new angular project
    ng new project-name
    



    // create a module 
    ng generate module custom-if
    


    이제 사용자 지정 지시문을 만들어 보겠습니다.

    // create a custom directive
    ng generate directive
    


    생성된 지시문은 다음과 같아야 합니다.

    import { Directive } from '@angular/core';
    
    @Directive({
      selector: '[customIf]',
    })
    export class customIfDirective {
      constructor() {}
    }
    


    전달된 값이 true인 경우 콘텐츠를 표시하는 기본 기능을 구현해 보겠습니다.

    <h2 *customIf="true">My visible content</h2>
    <h2 *customIf="false">My hidden content</h2>
    


    이를 달성하려면 몇 가지 요소가 필요합니다.

    콘텐츠 표시 여부를 결정하는 입력(@Input)
    조건부로 표시하려는 템플릿에 대한 참조(TemplateRef)
    Angular 보기에 대한 액세스 권한을 제공하는 컨테이너(ViewContainerRef)@input는 Angular의 일반 클래스 필드 데코레이터 속성일 수 있습니다. 표시된 예제 코드*customIf="true"에서와 같이 작동하려면 특성의 선택기와 동일한 속성 이름을 지정해야 합니다.

    import { Directive, Input } from '@angular/core';
    
    @Directive({
      selector: '[customIf]',
    })
    export class IfDirective {
     @Input() set customIf(show: boolean) {
        //code goes here
      }
    
      constructor() {}
    }
    


    이제 지시문에는 콘텐츠를 표시하는 값이 있으며 TemplateRef 및 ViewContainerRef 인스턴스도 필요합니다. @angular/core에서 가져와서 주입하면 됩니다.

    import { TemplateRef, ViewContainerRef } from '@angular/core';
    
    constructor(
        private templateRef: TemplateRef<unknown>,
        private vcr: ViewContainerRef
      ) {}
    


    이제 ViewContainerRef's 참조this.vcr.createEmbeddedView(this.templateRef) 메서드를 사용하여 표시하고 this.vcr.clear() 메서드를 사용하여 콘텐츠를 제거할 수 있습니다.

    이것이 최종 코드의 모습입니다.

    @Directive({
      selector: '[customIf]',
    })
    export class IfDirective {
    @Input() set customIf(value: boolean) {
        this._renderTemplate(value)l
      }
    
    constructor(
        private templateRef: TemplateRef<unknown>,
        private vcr: ViewContainerRef
      ) {}
    
    private _renderTemplate(show: boolean) {
        this.vcr.clear();
        if (show) {
          this.vcr.createEmbeddedView(this.templateRef);
        }
      }
    }
    


    와우! 🥳 *customIf를 성공적으로 생성했습니다. 이제 다른 템플릿 생성에 집중하겠습니다.
    그럼 어떻게 작동하는지 알아볼까요?

    How do we achieve this behaviour in our custom directive? This is where understanding the "syntactic sugar" that stands behind the structural directives is crucial.





    위의 이미지 예시를 보면 else 속성이 실제로 ngIfElse 입력 매개변수가 되고 있음을 의미합니다.

    따라서 selector (customIf) + else (Else) = customIfElse로 else 템플릿에 액세스할 수 있습니다.

    @Input() customIfElse?: TemplateRef<unknown>;
    


    이제 코드는 다음과 같습니다.

    @Directive({
      selector: '[customIf]',
    })
    export class IfDirective {
    @Input() set customIf(value: boolean) {
        this._renderTemplate(value)l
      }
    @Input() customIfElse?: TemplateRef<unknown>;
    constructor(
        private templateRef: TemplateRef<unknown>,
        private vcr: ViewContainerRef
      ) {}
    
    private _renderTemplate(show: boolean) {
        this.vcr.clear();
        if (show) {
          this.vcr.createEmbeddedView(this.templateRef);
        } else if (this.customIfElse) {
          this.vcr.createEmbeddedView(this.customIfElse);
        }
      }
    }
    


    요약



    이 문서에서는 추가 입력을 처리하는 간단한 사용자 지정 구조 지시문을 만드는 방법을 배웠습니다. 우리는 structure directive 뒤에 있는 통사적 설탕과 그것이 어떻게 directive의 입력으로 변환되는지를 다루었습니다.

    질문이 있는 경우 언제든지 으로 트윗하거나 DM을 보낼 수 있습니다. 기꺼이 도와드리겠습니다!

    linkedIn을 통해 나와 연결:

    좋은 웹페이지 즐겨찾기