Within my application, there is a unique feature where components are dynamically generated through a *ngFor loop. Here is an example of how it is implemented:
<div *ngFor="let actionCategory of actionCategories | keyvalue">
<h2>{{actionCategory.key}}</h2>
<div *ngFor="let action of actionCategory.value | keyvalue">
<app-gearset [action]="action"></app-gearset>
</div>
<button mat-button (click)="addComponent(actionCategory)">Add another set</button>
</div>
Users can further enhance their experience by adding more components through the button connected to the addComponent()
function. Take a look at the function below:
addGearSetComponent(actionCategory) {
this.actionCategories[actionCategory.key][Object.keys(this.actionCategories[actionCategory.key]).length] = {};
}
Upon invoking this function, a new empty object is appended to the designated actionCategory
object, resulting in the addition of a new component to the relevant section of the application. However, the challenge arises when the existing components lose their state each time a new one is added.
Is there a way to preserve the state of the existing components within the object, despite modifications made to the object they are associated with? Alternatively, is there a more effective approach to dynamically creating components based on a sophisticated object structure?