Nice programing

구성 요소에서 사용되는 지시문에 대한 참조 가져 오기

nicepro 2020. 12. 29. 08:27
반응형

구성 요소에서 사용되는 지시문에 대한 참조 가져 오기


템플릿이 다음과 같은 구성 요소가 있습니다.

<div [my-custom-directive]>Some content here</div>

MyCustomDirective여기에 사용 클래스 인스턴스에 대한 액세스 권한이 필요합니다 . 하위 구성 요소에 대한 액세스 권한을 얻으려면 ViewChild쿼리를 사용 합니다.

자식 지시문에 액세스하는 것과 동등한 기능이 있습니까?


주석의 exportAs속성을 사용할 수 있습니다 @Directive. 상위 뷰에서 사용할 지시문을 내 보냅니다. 상위 뷰에서 뷰 변수에 바인딩하고 .NET을 사용하여 상위 클래스에서 액세스 할 수 있습니다 @ViewChild().

플 런커를 사용한:

@Directive({
  selector:'[my-custom-directive]',
  exportAs:'customdirective'   //the name of the variable to access the directive
})
class MyCustomDirective{
  logSomething(text){
    console.log('from custom directive:', text);
  }
}

@Component({
    selector: 'my-app',
    directives:[MyCustomDirective],
    template: `
    <h1>My First Angular 2 App</h1>

    <div #cdire=customdirective my-custom-directive>Some content here</div>
    `
})
export class AppComponent{
  @ViewChild('cdire') element;

  ngAfterViewInit(){
    this.element.logSomething('text from AppComponent');
  }
}

최신 정보

의견에서 언급했듯이 위의 접근 방식에 대한 또 다른 대안이 있습니다.

를 사용하는 대신 exportAs직접 @ViewChild(MyCustomDirective)또는@ViewChildren(MyCustomDirective)

다음은 세 가지 접근 방식의 차이점을 보여주는 몇 가지 코드입니다.

@Component({
    selector: 'my-app',
    directives:[MyCustomDirective],
    template: `
    <h1>My First Angular 2 App</h1>

    <div my-custom-directive>First</div>
    <div #cdire=customdirective my-custom-directive>Second</div>
    <div my-custom-directive>Third</div>
    `
})
export class AppComponent{
  @ViewChild('cdire') secondMyCustomDirective; // Second
  @ViewChildren(MyCustomDirective) allMyCustomDirectives; //['First','Second','Third']
  @ViewChild(MyCustomDirective) firstMyCustomDirective; // First

}

최신 정보

Another plunker with more clarification


It appears that since @Abdulrahman's answer, directives can no longer be accessed from @ViewChild or @ViewChildren as these pass only items on the DOM element itself.

Instead, you must access directives using @ContentChild/@ContentChildren.

@Component({
    selector: 'my-app',
    template: `
    <h1>My First Angular 2 App</h1>

    <div my-custom-directive>First</div>
    <div #cdire=customdirective my-custom-directive>Second</div>
    <div my-custom-directive>Third</div>
    `
})
export class AppComponent{
  @ContentChild('cdire') secondMyCustomDirective; // Second
  @ContentChildren(MyCustomDirective) allMyCustomDirectives; //['First','Second','Third']
  @ContentChild(MyCustomDirective) firstMyCustomDirective; // First
}

There is also no longer a directives property on @Component attribute.

ReferenceURL : https://stackoverflow.com/questions/36345618/get-reference-to-a-directive-used-in-a-component

반응형