I can't find anywhere how to create reference to a component that I create dynamically from array?
HTML
<div *ngFor="let item of items">
<my-component [data]="item.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
Example:
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>
Thanks
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With