【问题标题】:Angular 5 Material Data Table Does Not Update On SortAngular 5 材料数据表在排序时不更新
【发布时间】:2018-08-23 08:05:38
【问题描述】:

我已经阅读了我不知道有多少示例,据我所知,我正确地遵循了示例,但是当我单击标题时列没有更新。

-我在 app.module.ts 中包含了 MatSortModule

-我在 mat-table 中包含了 matSort

-我在我希望能够排序的列的标题单元格中包含了 mat-sort-header(所有列)

-我已经包含了@ViewChild(MatSort) sort: MatSort;以及相应的

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }

我看不出还剩下什么。这是我的代码 sn-p:

<mat-table #table [dataSource]="dataSource" matSort class="dataTable">

    <!-- Name Column -->
    <ng-container matColumnDef="name">
        <mat-header-cell 
            *matHeaderCellDef 
            fxLayout="row" 
            fxLayoutAlign="start center" 
            mat-sort-header
            class="clickable"
        > 
            Product Name 
        </mat-header-cell>

        <mat-cell 
            *matCellDef="let item" 
            class="table-cell-content"
        > 
            {{item.name}} 
        </mat-cell>
    </ng-container>

...

defaultData: Array<Object> = null;
dataSource = new MatTableDataSource(this.defaultData);

@ViewChild(MatSort) sort: MatSort;

constructor(private getDataService: GetDataService) { 
  this.getDataService.getData()
    .subscribe(data => {
      this.defaultData = data;
      this.dataSource.data = this.defaultData;
    },
    err => console.log(err));
}

...

ngAfterViewInit() {
  this.dataSource.sort = this.sort;
}

【问题讨论】:

  • 出于好奇,这是该组件上唯一的表吗?如果同一个组件中有多个表,则必须采用一种奇怪的方法。
  • 是的,它是唯一的表。什么看起来很奇怪?

标签: angular datatable angular-material


【解决方案1】:

我能想到的唯一可能是您的问题是您可能不应该将数据直接分配给.dataSource 属性的.data 属性。直接修改这个属性可能会导致排序不理解它应该首先处理哪些数据,但我不能肯定地说(只是在黑暗中拍摄)。创建new MatTableDataSource() 引用应该会触发内置于 CDK 表结构中的 Observable 序列的反应性,这应该允许进行排序。

constructor(private getDataService: GetDataService) { 
  this.getDataService.getData()
    .subscribe(data => {
      // Your code:
      // this.defaultData = data;
      // this.dataSource.data = this.defaultData;
      
      // What I would do:
      this.defaultData = data;
      this.dataSource = new MatTableDataSource(data);
    },
    err => console.log(err));
}

【讨论】:

    【解决方案2】:

    您可以使用 underscorejs 对数据进行排序,并且材料表将被刷新或使用 MatTableDataSource 创建一个新实例。

    this.myDataSource = _.sortBy(initialData, 'fieldToSort' );
    

    this.myDataSource = new MatTableDataSource(initialData);
    

    【讨论】:

      猜你喜欢
      • 2018-12-07
      • 2019-05-19
      • 2018-10-29
      • 2019-01-03
      • 1970-01-01
      • 2021-01-20
      • 2021-07-17
      • 1970-01-01
      • 2019-12-27
      相关资源
      最近更新 更多