我有一个组件的模板看起来像这样:
- <div [my-custom-directive]>Some content here</div>
我需要访问这里使用的MyCustomDirective类实例。当我想访问一个子组件时,我使用ng.core.ViewChild查询。是否有一个等同的功能来访问子指令?
您可以使用@Directive注释的exportAs属性。它导出要在父视图中使用的指令。从父视图,您可以将其绑定到视图变量,并使用@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',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
- }
更新