Search code examples
angularviewchildren

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.

enter image description here

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


Solution

  • 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-