繁体   English   中英

Angular.js 2:指令的访问组件

[英]Angular.js 2: Access component of a directive

考虑以下Parent模板的代码段:

<div *ngFor= "let event of events" >
     <event-thumbnail [theEvent] = 'event'></event-thumbnail>                    
</div>

event-thumbnail组件的定义也是:

export class EventThumbnailComponent{
  intoroduceYourself(){
      console.log('I am X');
  }
}

Parent组件类中,我要遍历所有生成的event-thumbnail元素,访问每个元素下方的组件,并在其中一个上调用introduceYourself函数。

您想使用@ViewChildren()装饰器来获取视图中特定组件类型的所有实例的列表:

class ParentComponent implements AfterViewInit {
    @ViewChildren(EventThumbnailComponent)
    eventThumbnails: QueryList<EventThumbnailComponent>;

    ngAfterViewInit(): void {
        // Loop over your components and call the method on each one
        this.eventThumbnails.forEach(component => component.introduceYourself());

        // You can also subscribe to changes...
        this.eventThumbnails.changes.subscribe(r => {             
            // Do something when the QueryList changes
        });
    }
}

每当将此组件的一个实例添加到视图中或从视图中删除时, eventThumbnails属性都将更新。 注意eventThumbnails没有设置直到ngAfterViewInit

有关更多信息,请参见此处的文档: https : //angular.io/docs/ts/latest/api/core/index/ViewChildren-decorator.html

您的子组件应该具有@Input() theEvent才能访问您传递的事件。 然后,您可以使用以下生命周期挂钩:

ngOnInit(){
   introduceYourself(){
      console.log('I am X');
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM