Angular 6 mat-table 不会排序
Angular 6 mat-table won't sort
我有一个 Angular material table 有两个字段:
<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() 和其他几个地方附加排序,但无论我做什么都不起作用。
有什么想法吗?
您需要做一些更改,将代码移至 ngAfterViewInit
,因为 MatSort
在 ngAfterViewInit
之前不可用,并初始化 table 数据源,如下所示:
this.dataSource = new MatTableDataSource(this.results);
我有一个 Angular material table 有两个字段:
<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() 和其他几个地方附加排序,但无论我做什么都不起作用。
有什么想法吗?
您需要做一些更改,将代码移至 ngAfterViewInit
,因为 MatSort
在 ngAfterViewInit
之前不可用,并初始化 table 数据源,如下所示:
this.dataSource = new MatTableDataSource(this.results);