角度5物料数据表在排序

时间:2018-03-14 17:06:05

标签: angular datatable angular-material

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

- 我在我的app.module.ts

中包含了MatSortModule

- 我已经在mat-table上加入了matSort

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

- 我已经包含@ViewChild(MatSort)排序:MatSort;和相应的

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

我不知道还剩下什么。这是我的代码片段,任何帮助都将不胜感激。

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

2 个答案:

答案 0 :(得分:0)

我唯一能想到的可能是你的问题是你可能不应该直接将数据分配给.data属性的.dataSource属性。有可能直接修改这个属性导致排序不能理解它应该首先处理哪些数据,但我不能肯定地说(这里只是在黑暗中拍摄)。创建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));
}

答案 1 :(得分:0)

您可以使用underscorejs对数据进行排序,然后将刷新材质表,或使用MatTableDataSource创建新实例。

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

this.myDataSource = new MatTableDataSource(initialData);