Select dynamic created (custom) component element


#1

Hi,
I’d like to know if someone can tell/advise me about how I can select / use a dynamically created component.

Example case:

mypage.ts
public items: any[] = [{id: 1, value: "" }, {id: 2, value: "" }, {id: 3, value: "" }];
public arrayOfComponents: CustomInputCompComponent[] = [] ;
...
  triggerComponent(i: any){
    this.arrayOfComponents[i.id].submitValue(); 
     // |--> this will trigger an event output from the component returning as (reaction) in my html
  }
  saveItem(event: any, item: any){
    console.log(event); // log the value returning from the input component
    // do some other stuff based on the item.id and returned value from the event
}

mypage.html
<ion-item *ngFor="let i of items"> 
  <custom-input-comp (reaction)="saveItem($event, i)"></custom-input-comp>  
  <button ion-button (click)="triggerComponent(i)">Test component {{i.id}}</button
</ion-item>

So basically my question is… How can I add every generated component to the ‘arrayOfComponents’ so I can access them with the index of the item id.

What I had in mind is something like this, but I couldn’t figure out the correct syntax?

  ionViewDidLoad(){
    this.items.forEach((item) => {
      this.arrayOfComponents[item.id] = ??????? ; // ==> the component in the html
    });
  }

Btw. I don’t mind using a different approach than what I have. Please advice :blush:
Thanks…


#2

Hello,

maybe I understood you wrong, but maybe this helps. https://www.joshmorony.com/the-difference-between-viewchildren-and-contentchildren/

Otherwise, you have your array and you looking more for something like this. https://blog.angular-university.io/angular-2-ngfor/

Best regards, anna-liebt


#3

Yes viewchildren was exactly what I was looking for. Thank you for pointing me in the right direction.