获取对组件中使用的指令的引用

问题描述 投票:53回答:2

我有一个组件,其模板看起来像这样:

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

我需要访问这里使用的MyCustomDirective类实例。当我想访问子组件时,我使用ViewChild查询。

是否有相同的功能来访问子指令?

angular angular2-directives angular-template
2个回答
89
投票

您可以使用exportAs注释的@Directive属性。它导出要在父视图中使用的指令。在父视图中,您可以将其绑定到视图变量,并使用@ViewChild()从父类访问它。

使用plunker的示例:

@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


17
投票

从@ Abdulrahman的回答看来,无法再从@ViewChild@ViewChildren访问指令,因为这些指令只传递DOM元素本身的项目。

相反,您必须使用@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
}

directives属性上也不再有@Component属性。

© www.soinside.com 2019 - 2024. All rights reserved.