我有一个组件,其模板如下所示:
<div [my-custom-directive]>Some content here</div>
需要访问 MyCustomDirective
这里使用的类实例。当我想访问子组件时,我使用 ViewChild
查询。是否有等效的功能来访问子指令?
答案当然是可以的:
方法1:可以使用 exportAs
@Directive
的属性(property)注释。它导出要在父 View 中使用的指令。从父 View ,您可以将其绑定(bind)到 View 变量并使用 @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');
}
}
方法2:
不使用 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
}
参考资料:https://stackoverflow.com/questions/36345618/get-reference-to-a-directive-used-in-a-component