简体   繁体   English

如何在Angular中访问子组件对象

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

I have parent component id="componentOne" where is included another child component <app-buttons> : 我有父组件id="componentOne" ,其中包含另一个子组件<app-buttons>

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

Inside component app-buttons there is: 在组件app-buttons内部有:

 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 ? 那么,如何在初始化this.buttonUsage = new ButtonUsage之后从父组件获取对this.buttonUsage访问?

You can access using the viewChild and your component instance will be available in ngAfterViewInit 您可以使用viewChild进行访问,您的组件实例将在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 如果您有多个孩子,则可以在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