简体   繁体   中英

How to get access to child component object in Angular

I have parent component id="componentOne" where is included another child component <app-buttons> :

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

Inside component app-buttons there is:

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

So, how to get access to this.buttonUsage from parent component after initialization this.buttonUsage = new ButtonUsage ?

You can access using the viewChild and your component instance will be available in ngAfterViewInit

@ViewChild(AppButtonsComponent) appButtonsViewChild: AppButtonsComponent;


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

if you have multiple children you can use @ViewChildren decorator along side the QueryList generic type

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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