加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 08:14:07 所属栏目:安全 来源:网络整理
导读:我有一个组件的模板看起来像这样: div [my-custom-directive]Some content here/div 我需要访问这里使用的MyCustomDirective类实例。当我想访问一个子组件时,我使用ng.core.ViewChild查询。是否有一个等同的功能来访问子指令? 您可以使用@Directive注释的
我有一个组件的模板看起来像这样:
<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

}

更新

Another plunker with more clarification

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读