簡體   English   中英

如何在Angular中訪問子組件對象

[英]How to get access to child component object in Angular

我有父組件id="componentOne" ,其中包含另一個子組件<app-buttons>

<div id="componentOne">
    <app-buttons
    [component]="'WeeklyScheduleComponent'"
    [buttonTypes]="['add', 'filter']"
    [position]="'right-bottom'"
  ></app-buttons>
</div>

在組件app-buttons內部有:

 ngOnInit() {
    this.buttonUsage = new ButtonUsage(this.component, this.buttonTypes);
  }

那么,如何在初始化this.buttonUsage = new ButtonUsage之后從父組件獲取對this.buttonUsage訪問?

您可以使用viewChild進行訪問,您的組件實例將在ngAfterViewInit中可用

@ViewChild(AppButtonsComponent) appButtonsViewChild: AppButtonsComponent;


ngAfterViewInit() {
 console.log(this.appButtonsViewChild.buttonUsage );
}

如果您有多個孩子,則可以在QueryList泛型類型旁邊使用@ViewChildren裝飾器

@ViewChildren(AppButtonsComponent) appButtonsViewChildren: QueryList<AppButtonsComponent>;

ngAfterViewInit() { 
  let buttons: AppButtonsComponent[] = this.appButtonsViewChildren.toArray();
  console.log(buttons);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM