简体   繁体   English

在添加带有拼接的元素后更新 angular 4 中的数组?

[英]Updating an array in angular 4 after adding an element with splice?

I have a list in Angular displayed in table, I want to add an element in specific position.我在表格中显示了一个 Angular 列表,我想在特定位置添加一个元素。 I used我用了

array.splice(index,0,element);             

In the console everything is fine, the element is added at the correct position, but in HTML the table is not updated, the new element element is displayed in the position index and index+1 ( the old value of the position index+1 does not appear)在控制台中一切正常,元素被添加到正确的位置,但在 HTML 中表格没有更新,新元素element显示在位置indexindex+1 (位置index+1的旧值)没有出现)

在此处输入图片说明

here is the function :这是功能:

  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);
        });
}

these solutions give me the result in the picture, the new element is displayed in the second and third position这些解决方案给了我图片中的结果,新元素显示在第二个和第三个位置

PS: when I use push it works fine, but I have to add it in a specific index PS:当我使用 push 时它工作正常,但我必须将它添加到特定索引中

I tried the way you mentioned and it seems to be working fine(refer the demo below).我尝试了您提到的方法,它似乎工作正常(请参阅下面的演示)。 The issue seems to be with the data you are receiving.问题似乎与您收到的数据有关。

.ts file .ts 文件

  export class AppComponent {
  arr = [1, 2, 3];
  val = 999;
  clickHandler() {
    this.arr.splice(1, 0, this.val);
    this.val -= 1;
  }
}

.html file .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>

You can check the working example here demo您可以在此处查看工作示例演示

Splicing an element into the array does not change the Object reference hence not picked by change detection.将元素拼接到数组中不会更改对象引用,因此不会被更改检测选中。 You need a way to trigger change detection.您需要一种触发更改检测的方法。 Below should work下面应该工作

   this.detailsPieces.splice(index, 0, element);
   this.detailsPieces = [...this.detailsPieces]

Using spread operator, the above will trigger change detection使用扩展运算符,以上将触发变化检测

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM