Angular 更改模型后,为什么不在ngFor中更新模型?

Angular 更改模型后,为什么不在ngFor中更新模型?,angular,Angular,我有一个财产: public rows: any[]; 然后我在构造函数中填充这个数组: this.rows.push({"id": 1, "subject": "Subject", "scope": "Learn basics", "hours": 2}); 在模板中,我迭代数组,如下所示: <tr *ngFor="let p of rows; let i = index;"> 它不会改变模型,我看到数组中的一行与以前一样。Angular不会将数组识别为已更改,只要它的内容已

我有一个财产:

public rows: any[];
然后我在构造函数中填充这个数组:

this.rows.push({"id": 1, "subject": "Subject", "scope": "Learn basics", "hours": 2});
在模板中,我迭代数组,如下所示:

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

它不会改变模型,我看到数组中的一行与以前一样。

Angular不会将数组识别为已更改,只要它的内容已更改。要让它知道数组已更改,只需在删除元素后重新分配数组对象,它应该在DOM上更新:

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

重新分配数组,以便angular可以注意到更改并更新数组。在我的例子中,过滤数组而不是拼接它

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

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

相反,您可以执行以下操作


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

this.rows.splice(this.rows.length-1,1)
可能是从Angulars区域外的代码调用的,而更改检测无法识别更改。不,我在ClassMethod中的同一组件类中调用了它。请尝试:
this.rows=this.rows.splice(this.rows.length-1,1)并随后记录拼接。哦,您是使用AngularJs还是AngularJs(只是为了验证)返回带有spread运算符的新数组,还是使用filter获取元素。
this.rows=this.rows.splice(this.rows.length-1,1)总是返回与this.rows=[…rows]相同的行数?我错过了这个。现在编辑。但基本上,它只是从旧数组的元素创建一个新数组并重新分配它。这会使实际数组对象发生更改,从而使更改由其扩展运算符获取。您可以阅读更多关于:我使用TypeScriptIt不起作用:
this.rows.splice(this.rows.length-1,1);this.rows=[…this.rows]
array.splice(removeIndex, 1) // replaced with

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