0
votes

Code : https://stackblitz.com/edit/dynamic-child-inside-parent-component

Code description :

I have dynamically created child components while clicking on a button in the parent component.I have passed a input from parent to child component(@Input) to keep track of the button click counter value.But when i delete from the child component and add again i get the counter value wrong.I have restricted the button click to 5 times.

Example scenario : I have clicked the button 5 times so the child is rendered 5 times in case if i delete any one of the child component out of 5 (say i delete event 5 ) and click add event button from parent again i get duplicate of event 5 ?Is there a way to update the counter value in child components ? Any help would be really appreciated.Kindly see the example which i created to understand,Thanks in advance.

1
going by what you say you want, shouldnt it create a duplicate of event 5? - mast3rd3mon
You said what it does. But you didn't say what you wanted it to do. Besides, why aren't you just using ngFor to display your child components? - JB Nizet
@mast3rd3mon Yes if i delete event 1 and if i click add event button again i should get the missing event out of 5.So if i delete event 1 i i should get back what i deleted instead of the existing events. - Melvin
use an array to store which events have components? - mast3rd3mon
Use an array of 5 elements, initialized with events with a "hidden" flag, set to true. When you click "Add event", find the first hidden event, and set its hidden flag to false. Use ngFor to iterate over the 5 events, and use ngIf to only display an event if it's not hidden. - JB Nizet

1 Answers

3
votes

Here is your working app:

https://stackblitz.com/edit/dynamic-child-inside-parent-component-fygtyr

The only change is in travellers.component.ts in addComponent method and declared a class variable. The logic is to keep a track of the counters being displayed and assign a new value to the component on addition.

Hope it helps!