角度2:获取对组件中使用的指令的引用

前端之家收集整理的这篇文章主要介绍了角度2:获取对组件中使用的指令的引用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个组件的模板看起来像这样:
  1. <div [my-custom-directive]>Some content here</div>

我需要访问这里使用的MyCustomDirective类实例。当我想访问一个子组件时,我使用ng.core.ViewChild查询。是否有一个等同的功能来访问子指令?

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

示例使用plunker

  1. @Directive({
  2. selector:'[my-custom-directive]',exportAs:'customdirective' //the name of the variable to access the directive
  3. })
  4. class MyCustomDirective{
  5. logSomething(text){
  6. console.log('from custom directive:',text);
  7. }
  8. }
  9.  
  10. @Component({
  11. selector: 'my-app',directives:[MyCustomDirective],template: `
  12. <h1>My First Angular 2 App</h1>
  13.  
  14. <div #cdire=customdirective my-custom-directive>Some content here</div>
  15. `
  16. })
  17. export class AppComponent{
  18. @ViewChild('cdire') element;
  19.  
  20. ngAfterViewInit(){
  21. this.element.logSomething('text from AppComponent');
  22. }
  23. }

更新

正如评论中所提到的,上述方法还有另外一种选择。

而不是使用exportAs,可以直接使用@ViewChild(MyCustomDirective)或@ViewChildren(MyCustomDirective)

以下是一些代码来演示三种方法之间的区别:

  1. @Component({
  2. selector: 'my-app',template: `
  3. <h1>My First Angular 2 App</h1>
  4.  
  5. <div my-custom-directive>First</div>
  6. <div #cdire=customdirective my-custom-directive>Second</div>
  7. <div my-custom-directive>Third</div>
  8. `
  9. })
  10. export class AppComponent{
  11. @ViewChild('cdire') secondMyCustomDirective; // Second
  12. @ViewChildren(MyCustomDirective) allMyCustomDirectives; //['First','Second','Third']
  13. @ViewChild(MyCustomDirective) firstMyCustomDirective; // First
  14.  
  15. }

更新

Another plunker with more clarification

猜你在找的Angularjs相关文章