Why is not updated model in ngFor after changed mo

2020-06-27 09:42发布

问题:

I have an property:

public rows: any[];

Then I fill this array in constructor:

this.rows.push({"id": 1, "subject": "Subject", "scope": "Learn basics", "hours": 2});

In template I iterate array like as:

<tr *ngFor="let p of rows; let i = index;">

So, if I remove element from array:

this.rows.splice(this.rows.length - 1, 1);

It does not change model, I see as before one row in array.

回答1:

Angular doesn't recognise an array as having been changed if only it's contents have been changed. To let it know the array has changed just reassign the array object after removing an element and it should update on the DOM:

this.rows.splice(this.rows.length - 1, 1);
this.rows = [...this.rows];


回答2:

re-assign the array so that angular can notice a change and update the array



回答3:

In my case filtering array instead of splicing it worked out

array.splice(removeIndex, 1) // replaced with

array = array.filter(
  (element, index) => removeIndex !== index
)


回答4:

Instead you could do the following

this.rows.splice(this.rows.indexOf(this.rows.length - 1), 1);



标签: angular