[英]Sorting is not working on Material Table in Angular
我正在關注 angular 材料網站上的基本示例。 它顯示具有正確數據的表,但排序不起作用。
這是堆棧閃電戰: https://stackblitz.com/edit/angular-jj5qub?file=src%2Fapp%2Ftable-sorting-example.ts
TS 文件
export class TableSortingExample implements OnInit, AfterViewInit {
ELEMENT_DATA: any;
dataSource: MatTableDataSource<any>;
@ViewChild(MatSort) sort: MatSort;
ngOnInit() {
this.ELEMENT_DATA = {
customerHeader: ["ID", "Name", "Address"],
customerDataRows: [
["1", "Mark", "10"],
["2", "John", "110"],
["3", "John", "110"]
]
};
this.dataSource = new MatTableDataSource(
this.ELEMENT_DATA.customerDataRows
);
}
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
}
HTML 文件
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<ng-container
*ngFor="let custColumn of ELEMENT_DATA.customerHeader; let colIndex = index"
matColumnDef="{{ custColumn }}"
>
<mat-header-cell *matHeaderCellDef mat-sort-header
>{{ custColumn }}</mat-header-cell
>
<mat-cell *matCellDef="let customerRow">
{{customerRow[colIndex]}}
</mat-cell>
</ng-container>
<mat-header-row
*matHeaderRowDef="ELEMENT_DATA.customerHeader; "
></mat-header-row>
<mat-row *matRowDef="let row; columns: ELEMENT_DATA.customerHeader"></mat-row>
</table>
嘗試使用鍵/值對象而不是簡單的 arrays,其信息取決於其 position。 例如,快速更改代碼以轉換對象中的客戶數據 arrays 使您的代碼對表進行排序。
在table-sorting-example.ts
中,更改為:
customerDataRows: [
["1", "Mark", "10"],
["2", "John", "110"],
["3", "John", "110"]
]
至:
customerDataRows: [
{ ID: "1", Name: "Mark", Address: "10" },
{ ID: "2", Name: "John", Address: "110" },
{ ID: "3", Name: "John", Address: "110" }
]
在table-sorting-example.html
從{{customerRow[colIndex]}}
到{{customerRow[custColumn]}}
PS:我喜歡小寫的所有鍵,但只想快速更改代碼以顯示結果。
查看包含更改的項目的分支。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.