【问题标题】:Angular 6 mat table DOM not updating after splicing the data sourceAngular 6 mat table DOM在拼接数据源后不更新
【发布时间】:2019-03-18 19:12:32
【问题描述】:

我有一个mat-table

<mat-table #table [dataSource]="orders" [trackBy]="$index">

    <ng-container matColumnDef="id">
      <mat-header-cell *matHeaderCellDef> ID </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.id}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="deliver_on">
        <mat-header-cell *matHeaderCellDef> Deliver On </mat-header-cell>
        <mat-cell *matCellDef="let row" [style.color]="row.deliver_on"> {{row.deliver_on}} </mat-cell>
    </ng-container>


    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row [ngClass]="row.highlight_row"  *matRowDef="let row; columns: displayedColumns;"></mat-row>

</mat-table>
<mat-paginator [length]="pageLength" [pageSize]="pageSize" (page)="next($event)">
</mat-paginator>

我想更新特定逻辑中的行。

但是,当我更新数据源 (ARRAY SPLICE) 时,DOM 并没有改变

var order = data.payload.order;
var index = this.orders.findIndex((orders) => orders.id === order.id);

Object.defineProperty(order, "highlight_row", {
    value: 'highlight_row',
    writable: true,
    enumerable: true,
    configurable: true
});

if (index > -1) {
    // update at same position
    this.orders.splice(index, 1, order);
}
else {
    this.orders = [...this.orders, order];
}

【问题讨论】:

标签: javascript html angular typescript angular-material


【解决方案1】:

来自材料 cdk 文档和@Input() dataSource: CdkTableDataSourceInput&lt;T&gt;

如果提供了数据数组,则必须在 数组的对象被添加、删除或移动。这可以通过 调用 renderRows() 函数,该函数将呈现差异,因为 最后一张表渲染。如果更改了数据数组引用,则表 将自动触发对行的更新。

此外,从 JavaScript 的角度来看,splice 方法会改变(更改)数组,因此不会更改数组引用。

参考:https://material.angular.io/cdk/table/api

【讨论】:

    【解决方案2】:

    更改MatTableDataSource 中的元素后,您可以强制表格重绘

    this.order._updateChangeSubscription();
    
    

    【讨论】:

      【解决方案3】:

      你可能不得不在拼接后手动触发changetetor

      if (index > -1) {
          // update at same position
          this.orders.splice(index, 1, order);
          this.changeDetectorRefs.detectChanges();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-08
        • 2018-03-26
        • 1970-01-01
        • 2018-07-02
        • 2019-04-05
        • 2019-06-20
        • 2019-07-28
        • 2019-02-14
        相关资源
        最近更新 更多