在更改数据源后,需要手动重新设置排序表头的数据源。这可以通过以下步骤实现:
在 HTML 模板中,找到包含排序表头的 mat-table 元素,将其绑定到模板引用变量中:
在组件类中,使用 ViewChild 装饰器和 @Input() 装饰器声明这个引用变量:
@ViewChild('table') table: MatTable
@Input() dataSource: MatTableDataSource
在更改数据源后,重新设置表头的数据源:
this.dataSource = new MatTableDataSource(data);
this.table.dataSource = this.dataSource;
现在,表头排序应该正常工作了。
完整的代码示例:
HTML 模板:
Name
{{item.name}}
Age
{{item.age}}
组件类:
import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { MatTableDataSource, MatSort } from '@angular/material';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss']
})
export class TableComponent implements OnInit {
displayedColumns: string[] = ['name', 'age'];
dataSource: MatTableDataSource;
@ViewChild(MatSort, { static: true }) sort: MatSort;
@ViewChild('table') table: MatTable;
@Input() data: any[];
ngOnInit() {
this.dataSource = new MatTableDataSource(this.data);
this.dataSource.sort = this.sort;
this.table.dataSource = this.dataSource;
}
ngOnChanges(changes) {
if (changes.data) {
this.dataSource = new MatTableDataSource(changes.data.currentValue);
this.dataSource.sort = this.sort;
this.table.dataSource = this.dataSource;
}