[英]Updating an array in angular 4 after adding an element with splice?
我在表格中顯示了一個 Angular 列表,我想在特定位置添加一個元素。 我用了
array.splice(index,0,element);
在控制台中一切正常,元素被添加到正確的位置,但在 HTML 中表格沒有更新,新元素element
顯示在位置index
和index+1
(位置index+1
的舊值)沒有出現)
這是功能:
addLineModified(id) {
let index = this.detailsPieces.findIndex((x) => x.id === id);
this.detailsPiecesService
.getDetailsPieceBylineModified(this.quotation.id, id)
.subscribe((element: DetailsPieces) => {
this.detailsPieces.splice(index, 0, element);
});
}
這些解決方案給了我圖片中的結果,新元素顯示在第二個和第三個位置
PS:當我使用 push 時它工作正常,但我必須將它添加到特定索引中
我嘗試了您提到的方法,它似乎工作正常(請參閱下面的演示)。 問題似乎與您收到的數據有關。
.ts 文件
export class AppComponent {
arr = [1, 2, 3];
val = 999;
clickHandler() {
this.arr.splice(1, 0, this.val);
this.val -= 1;
}
}
.html 文件
<table >
<tr>
<th>Index</th>
</tr>
<tr *ngFor="let index of arr"><td>{{index}}</td></tr>
</table>
<button (click)="clickHandler()">add at index 2</button>
您可以在此處查看工作示例演示
將元素拼接到數組中不會更改對象引用,因此不會被更改檢測選中。 您需要一種觸發更改檢測的方法。 下面應該工作
this.detailsPieces.splice(index, 0, element);
this.detailsPieces = [...this.detailsPieces]
使用擴展運算符,以上將觸發變化檢測
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.