簡體   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