您可以使用exportAs
的财产@Directive
注解。它导出要在父视图中使用的指令。从父视图中,您可以将其绑定到视图变量并使用以下命令从父类访问它@ViewChild()
.
示例与plunker http://plnkr.co/edit/pftUzfHKJL6yhdexKE98?p=preview:
@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');
}
}
Update
正如评论中提到的,上述方法还有另一种替代方法。
而不是使用exportAs
, 可以直接使用@ViewChild(MyCustomDirective)
or @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
}
Update
另一个有更多说明的笨蛋 http://plnkr.co/edit/kkz6Q919WBQe3h35Pl3L?p=preview