Having multiple nested arrays displaying data through HTML recursion in Angular, I am faced with the task of updating specific fields. Directly editing a field is simple and involves assigning its instance to a variable.
arr=[{
"name":"field-1",
"fields":[
{
"name":"Field-2",
"fields":[]
},
{
"name":"field-3",
"fields":[
{
"name":"field-3",
"fields":[]
}
]
}
]
}]
If I want to edit a field, I simply assign its instance to a variable.
<ng-template #recursion let-data="data">
<ng-container *ngFor="let item of data">
<div>
{{item.name}}
<button (click)="edithThis(item)">Edit</button>
</div>
<div *ngIf="item.fields && item.fields.length">
<ng-container *ngTemplateOutlet="recursion;context:{data:item.fields}"></ng-container>
</div>
</ng-container>
</ng-template>
export class Component{
data_to_edit: any;
edithThis(selected: any) {
this.data_to_edit=selected
}
}
After modifying data_to_edit
, the original value changes as well. To enable reverting back to the old value upon cancellation, two variables are utilized.
export class Component {
data_to_edit: any;
instance_of_data: any;
edithThis(selected: any) {
this.data_to_edit = { ...selected }
this.instance_of_data = selected
}
}
One variable is used for modification, while the other ensures that the original value is updated after confirming the change.