简体   繁体   中英

Access to child component reference for Angular @ViewChildren

I'm creating a number of ModuleItemComponents using the following Angular markup:

<div #moduleItems *ngFor="let module of seriesItem.modules; let i = index">
    <app-module-item [videoModule]="module" ></app-module-item>    
</div>

and the following code lives in the corresponding.ts file:

  @ViewChildren('moduleItems') moduleItems;

I'm using code in the ngAfterViewInit event to try and get a reference to each ModuleItemComponent:

ngAfterViewInit() {
   let items: [];
   items = this.moduleItems.map((m) => m.nativeElement.firstChild);
   items.forEach((m) => {
     const thisModule = (m as ModuleItemComponent);
     thisModule.onSelectionMade.subscribe((result: VideoModule) => {
       this.deselectOthers(result);
     });
   });
 }

However, I get an error at the ".subscribe" line because the type of thisModule is app-module-item, not ModuleItemComponent.

在此处输入图像描述

I'm sure I'm doing something wrong - just not sure how to do this right. Any help appreciated.

You need put the variable reference in the <app-module-item>

<app-module-item #moduleItems ...>

But in this case, you can use the own name of the class and forget the variable reference

@ViewChildren(ModuleItemComponent) moduleItems:QueryList<ModuleItemComponent>

And you can do

ngAfterViewInit()
{
 
   this.moduleItems.forEach(item=>{
        ..item is a ModuleItemComponent.. 
        ..you has access to all his properties..
        ..e.g. item.onSelectionMade.subscribe(....)
    })
}

See that the name of the class is not between quotes -I supose the name of the class is ModuleItemComponent, else change for the name of the class-

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