【问题标题】:Angular 6 mat-table won't sortAngular 6 mat-table 不会排序
【发布时间】:2019-04-05 15:57:30
【问题描述】:

我有一个包含两个字段的 Angular 材质表:

<table mat-table [dataSource]="dataSource" matSort  class="mat-elevation-z8">
   <ng-container matColumnDef="Field1">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Field1</th>
      <td mat-cell *matCellDef="let element"> {{element.Field1}} </td>
   </ng-container>
   <ng-container matColumnDef="Field2">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Field2</th>
      <td mat-cell *matCellDef="let element"> {{element.Field2}} </td>
   </ng-container>
   <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
   <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

我导入以下模块:

Material.MatTableModule,
Material.MatSortModule,

然后我声明排序如下:

@ViewChild(MatSort) sort: MatSort;

我通过在构造函数中调用以下方法从外部 API 填充数据源:

       populateTable() {
            this.requestHttpService.getStuff()
                .subscribe(data => {
                        this.results = data;
                        this.dataSource = this.results;
                        this.dataSource.sort = this.sort;
                    },
                    ...

正如您所注意到的,我试图在加载数据源后附加排序。

我也尝试在 ngAfterViewInit() 和其他几个地方附加排序,但无论我做什么它都不起作用。

有什么想法吗?

【问题讨论】:

  • 您需要像setTimeout(() =&gt; {this.dataSource.sort = this.sort;}); 一样申请setTimeout。解释here
  • 刚试了还是不开心。
  • 请确保您的 matColumnDef 属性与您的数据模型相匹配。即您的数据源项目应该具有匹配的属性。此外,将您的 matsort 放入 html 中,例如
  • Raj - 如果不匹配,代码会抛出错误。
  • 啊!你错过的另一件事是this.dataSource = new MatTableDataSource(this.results);

标签: angular sorting mat-table


【解决方案1】:

您需要做一些更改,将代码移动到ngAfterViewInit,因为MatSort 直到ngAfterViewInit 才可用,并如下初始化表数据源:

this.dataSource = new MatTableDataSource(this.results);

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 2022-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多