Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create reference to a dynamically created component?

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

like image 422
Roman Šimík Avatar asked Jun 05 '26 00:06

Roman Šimík


1 Answers

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.

like image 135
SiddAjmera Avatar answered Jun 07 '26 13:06

SiddAjmera