javascript - Angular.js 2 : Access component of a directive

标签 javascript angular

考虑以下 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() 装饰器来获取 View 中特定组件类型的所有实例的列表:

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
        });
    }
}

只要在 View 中添加或删除此组件的实例,eventThumbnails 属性就会更新。请注意,eventThumbnails 直到 ngAfterViewInit 才设置。

请参阅此处的文档以获取更多信息: https://angular.io/docs/ts/latest/api/core/index/ViewChildren-decorator.html

关于javascript - Angular.js 2 : Access component of a directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42990704/

相关文章:

javascript - 如果其中一个子菜单项处于事件状态,则展开下拉菜单

javascript - 如何从 Javascript 添加 CSS 样式

angular - 在所有输入上触发模糊 Angular2 Reactive Forms

angular - "Can' t read the url"error for angular2 dynamic components with templateUrl

node.js - Angular:ngModel 插值在输入文本框中返回 NaN。如何显示号码

javascript - JS用字符串和字符串数字排序数组

javascript - 在 Rails 中迭代 ChartJS 的背景颜色数组

javascript - 你如何反向滚动......所以它从下到上?

javascript - Angular 2 将组件动态附加到 DOM 或模板

javascript - Observable<QuerySnapshot<DocumentData>> 类型上不存在属性 'then'