示例代码如下:
HTML:
Name
{{ row.name }}
Age
{{ row.age }}
TS:
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
@Component({
selector: 'app-table-sorting',
templateUrl: './table-sorting.component.html',
styleUrls: ['./table-sorting.component.css']
})
export class TableSortingComponent implements OnInit {
@ViewChild(MatSort, {static: true}) sort: MatSort;
dataSource = new MatTableDataSource([
{name: 'John', age: 25},
{name: 'Emily', age: 36},
{name: 'Bob', age: 19},
{name: 'Jane', age: 42},
]);
displayedColumns = ['name', 'age'];
ngOnInit() {
this.dataSource.sort = this.sort;
}
}