In a project in angular I have a table with several elements and in each row there is a button that is used to delete the corresponding row. In the button I inserted an event that on click calls a function and passes the id of the object:
<button mat-flat-button (click)="removePhase(phase.id)">
<span><mat-icon>close</mat-icon></span>
</button>
when pressed calls this function:
removePhase(id:number){
console.log(this.phase) /*First log*/
this.phase.forEach((element) => {
if (element.id != id) {
this.phaseRemove.push(element);
}
})
this.phaseRemove.forEach((element, index) => {
element.id = index;
})
this.phase = this.phaseRemove;
this.dataSource = new MatTableDataSource(this.phase);
console.log(this.phase) /*Second log*/
}
this is the phase object:
[
{
"id": 0,
"phaseName": "Phase 1"
},
{
"id": 1,
"phaseName": "Phase 2"
},
{
"id": 2,
"phaseName": "Phase 3"
},
{
"id": 3,
"phaseName": "Phase 4"
}
]
when the function is launched the first time everything works normally, while when I launch it a second time it loops the first for. I entered two console logs to see what happens and in the first one I get this object (in this thing I pressed the button to delete the object with id 0):
[
{
"id": 0,
"phaseName": "Phase 1",
},
{
"id": 0,
"phaseName": "Phase 2",
},
{
"id": 1,
"phaseName": "Phase 3",
},
{
"id": 2,
"phaseName": "Phase 4",
}
]
and in the second log, I get the correct object instead:
[
{
"id": 0,
"phaseName": "Phase 2",
},
{
"id": 1,
"phaseName": "Phase 3",
},
{
"id": 2,
"phaseName": "Phase 4",
}
]
As you can see the console log of the first object also sets the id 0 to the second object, I think this is the infinite for loop error, but I don't know how to solve it. Thank you.