[英]Sorting is not working on Material Table in Angular
I am following the basic example on angular material website.我正在关注 angular 材料网站上的基本示例。 It shows the table with correct data but sorting does not work.
它显示具有正确数据的表,但排序不起作用。
Here is the stackblitz: https://stackblitz.com/edit/angular-jj5qub?file=src%2Fapp%2Ftable-sorting-example.ts这是堆栈闪电战: https://stackblitz.com/edit/angular-jj5qub?file=src%2Fapp%2Ftable-sorting-example.ts
TS File 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 File 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>
Try using key/value objects instead of simple arrays with info that depends on their position.尝试使用键/值对象而不是简单的 arrays,其信息取决于其 position。 For example, a quick change to your code transforming your arrays of customer data in objects make your code sort the table.
例如,快速更改代码以转换对象中的客户数据 arrays 使您的代码对表进行排序。
In table-sorting-example.ts
, change from:在
table-sorting-example.ts
中,更改为:
customerDataRows: [
["1", "Mark", "10"],
["2", "John", "110"],
["3", "John", "110"]
]
to:至:
customerDataRows: [
{ ID: "1", Name: "Mark", Address: "10" },
{ ID: "2", Name: "John", Address: "110" },
{ ID: "3", Name: "John", Address: "110" }
]
And in table-sorting-example.html
from {{customerRow[colIndex]}}
to {{customerRow[custColumn]}}
在
table-sorting-example.html
从{{customerRow[colIndex]}}
到{{customerRow[custColumn]}}
PS: I like all keys in lowercase, but only wanted to change the code quickly to show you the result. PS:我喜欢小写的所有键,但只想快速更改代码以显示结果。
See a fork of your project with the changes.查看包含更改的项目的分支。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.