PrimeNG删除数据表行

PrimeNG delete row of datatable

我在从 p-datatable 中删除一行时遇到问题。

TS

public files: UploadFile[] = [];
deleteAttachement(index) {

    if (this.files.length > 0) {
        for(let file2 of this.files) {
            if (file2.fileEntry.isFile) {
                const fileEntry = file2.fileEntry as FileSystemFileEntry;
                fileEntry.file((file: File) => {
                    console.log("-------------");
                    console.log("File: "+file.name);
                });
            }
        }

        this.files.splice(index, 1);

        for(let file2 of this.files) {
            if (file2.fileEntry.isFile) {
                const fileEntry = file2.fileEntry as FileSystemFileEntry;
                fileEntry.file((file: File) => {
                    console.log("_______________");
                    console.log("File: "+file.name);
                });
            }
        }
    }

}

HTML

<p-dataTable [value]="files" *ngIf="files.length > 0">
<p-column>
  <ng-template let-index="rowIndex" pTemplate type="body">
    <p-button (onClick)="deleteAttachement(index)" icon="fa fa-fw fa-close"></p-button>
  </ng-template>
</p-column>
</p-dataTable>

我的代码正在记录正确的事情。看来我拼接对了。但是当我想更新视图中的数据表时,更改行:

this.files = this.files.splice(index, 1);

但是现在拼接错了,没有删除正确的行。有时它会删除多行,有时它什么也不删除。

你应该看看 PrimeNG 数据表的不可变 属性。

您需要知道的第一件事是,对于您希望在 p-dataTable 中看到的任何更新,必须有一个全新的数组对象应该传递给它的 [value] 参数这样 p-dataTable 就知道它需要重新渲染 table。通过这种方式,我们保留了对象的不变性,并且它具有非常好的性能影响。 Check this 了解有关不变性的更多信息。

splice 更新同一个数组,因此不会创建新的数组对象。查看 splice 详细信息 here

当您执行 this.files.splice(index, 1) 时,它会更新文件数组,但 this.files 指的是同一个对象,因此它不会被 PrimeNg 检测到。

每次要从中删除项目时都需要创建一个新的数组对象。这应该有效:

this.files = this.files.slice(0, index).concat( this.files.slice(index+1) );

slice 不会更新数组(在本例中为 this.files),而是根据给定的索引创建数组的新副本。所以,在上面一行中,我们创建了两组数组。第一个数组是从开始到给定的 index(不包括 index 处的项目),第二个数组是从给定的 index 之后到它的末尾。然后我们连接这两个数组以获得一个全新的数组,不包括位置 index.

的项目

this.files = this.files.filter((val,i) => i!=index);

参考Linkhttps://www.primefaces.org/primeng-4.3.0/#/datatable/crud

你好,上面的代码对我不起作用,我需要先获取行数据并将其用作索引,splice(index, 1) 将按预期工作。

const index: number = this.objArr.indexOf(rowData);//get index by passing the concern row data
        if (index !== -1) {
          this.objArr.splice(index, 1);
        }