htmlangulartypescriptangular9angular2-components

spawn/generate existing components dynamically in Angular 11


I'm doing an web application that is supposed to work like the contacts app that we have in our phones:

  1. Register contact info (name, email, number)
  2. Click on save Button
  3. List is updated immediately (here is my problem)

So I have a list.component (a grey mat-card) and a contact.component, (an orange mat-card).

I want to spawn a new contact.component inside of the list.component, and destroy it when the user select the delete button. It looks like this now

The data is passing fine, but I don't know how to add a new existing component inside another.


Solution

  • You could save the contacts inside a public array and then iterate over it inside the list-component:

      <list-component>
    <ng-container *ngFor="let contact of contactArray"> 
    <contact-component></contact-component>
     </ng-container>
    </list-component>
    

    When the user adds another contact, you can push it to the contactArray and the additional contact-component will appear