How to create reference to a dynamically created component

  • A+

I can't find anywhere how to create reference to a component that I create dynamically from array?


<div *ngFor="let item of items">     <my-component [data]=""></my-component> </div> 

I need to have access to every <my-component> (which will be created dynamically from the array) in the TypeScript code


The length of items array is 2. So then in TypeScript code I need to have something like this.

myComponent0 - reference to the 1. <my-component>

myComponent1 - reference to the 2. <my-component>

Even if you navigate me to some docs about this or anything that could help, I will be so gratefull



Use ViewChildren

import { ViewChildren, QueryList, ... } from '@angular/core';  export class AppComponent {    @ViewChildren(MyComponent) components: QueryList<MyComponent>    ...    ngAfterViewInit() {     this.components.forEach(componentInstance => console.log(componentInstance));   }    ...  } 

Here MyComponent is the exported name of the Component Class. This is generally of type QueryList so you can essentially treat it as an array and do the needful.

This will only be available after the AfterViewInit hook of the Component.

Here's a Sample StackBlitz for your ref.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: