我正在尝试在 mat-table 中实现排序,但它根本不起作用。我没有收到任何错误。
这是我的代码。
这是我的 component.ts 文件
export class TerminalsComponent implements OnInit {
cols: string[] = ['select', 'serialKey', 'cameras', 'status', 'activeSince', 'created', 'updated', 'addCamera', 'more'];
success: boolean;
message: string;
dataSource;
expandedElement: any;
initialSelection = [];
allowMultiSelect = true;
selection = new SelectionModel<any>(this.allowMultiSelect, this.initialSelection);
@ViewChild(MatSort) sort: MatSort;
constructor(public cs: Service) {
this.getTerminals();
}
masterToggle() {
this.isAllSelected() ?
this.selection.clear()
: this.dataSource.data.forEach(row => this.selection.select(row));
}
isAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.dataSource.data.length;
return numSelected === numRows;
}
// Expandable Row
isExpansionDetailRow(i: number, row: Object) {
return row.hasOwnProperty('detailRow');
}
getTerminals() {
this.cs.getTerminals().subscribe(
(response) => {
this.success = response.success;
this.message = response.msg;
if (response.success) {
this.dataSource = new MatTableDataSource(response.data);
this.dataSource.sort = this.sort;
console.log(this.dataSource);
}
setTimeout(function () {
this.message = "";
}.bind(this), 2000);
},
(error) => {
this.success = error.success;
this.message = "Cannot get terminals" + error.message;
}
);
}
ngOnInit() { }
}
终端,即 mat-table 的数据源,是嵌套对象的数组。serialKey 是一个字符串。
这是我的 component.html 文件的代码片段。我已将 mat-sort-header 添加到 serialKey 列。
<mat-table class="list-table" [dataSource]="dataSource" matSort matSortActive="serialKey" matSortDirection="asc">
<ng-container matColumnDef="serialKey">
<mat-header-cell mat-sort-header class="align-center" *matHeaderCellDef>Serial Key</mat-header-cell>
<mat-cell class="align-center" *matCellDef="let element">{{element.serial_num}}
</mat-cell>
</ng-container>
</mat-row>
</mat-table>
如果有人能告诉我我在这里缺少什么来对表格进行排序,那就太好了。