3

I have a child and a parent component as following:

<app-parent>
   <app-child> </app-child>
</app-parent>

How can I dynamically increase the number of children shown in the parent component? Something like I click on a button in the parent component and then a new child be added, like below:

<app-parent>
   <app-child> </app-child>
   <app-child> </app-child>
</app-parent>

2 Answers 2

3

Another more modern approach than using the ngFor directive:

<app-parent>
    @for (child of children; track child.id; let idx = $index) { 
        <app-child [index]="idx" [data]="child" />
    }
</app-parent>

Assuming that children is a collection of data grouped for each app-child component that you want to render and the app-child component has input properties to receive this data.

The @for block operator was recently added to Angular in version 17. I think this is a way more intuitive approach for repeatedly rendering elements on the page especially for people coming from languages such as Python or C#. More on the @for block here

Sign up to request clarification or add additional context in comments.

Comments

2

To dynamically add child components, you can do the following:

In parent.component.ts:

childrenComponent: number[] = [];

addChild() {
  this.childrenComponent.push(this.childrenComponent.length);
}

In parent.component.html:

<button (click)="addChild()">Add Child</button>

<app-child *ngFor="let child of childrenComponent"></app-child>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.