获取对组件中使用的指令的引用 [英] Get reference to a directive used in a component
问题描述
我有一个组件,其模板如下所示:
I have a component whose template looks something like this:
<div [my-custom-directive]>Some content here</div>
我需要访问这里使用的MyCustomDirective
类实例.当我想访问子组件时,使用ViewChild
查询.
I need access to the MyCustomDirective
class instance used here. When I want to get access to a child component, I use a ViewChild
query.
是否有等效功能可以访问子指令?
Is there an equivalent feature to get access to a child directive?
推荐答案
您可以使用@Directive
批注的exportAs
属性.它导出要在父视图中使用的指令.在父视图中,您可以将其绑定到视图变量,并使用@ViewChild()
从父类访问它.
You can use exportAs
property of the @Directive
annotation. It exports the directive to be used in the parent view. From the parent view, you can bind it to a view variable and access it from the parent class using @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');
}
}
更新
如评论中所述,上述方法还有另一种选择.
As mentioned in the comments, there is another alternative to the above approach.
代替使用exportAs
,可以直接使用@ViewChild(MyCustomDirective)
或@ViewChildren(MyCustomDirective)
Instead of using exportAs
, one could directly use @ViewChild(MyCustomDirective)
or @ViewChildren(MyCustomDirective)
以下代码演示了三种方法之间的区别:
Here is some code to demonstrate the difference between the three approaches:
@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
}
更新
这篇关于获取对组件中使用的指令的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!