下面是一个简单的示例,展示了如何使用Angular进行列排序的解决方法:
首先,你需要在你的Angular应用中引入@angular/material
库,以便使用Material Design风格的表格组件。
在你的组件中,首先导入所需的模块:
import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
export interface User {
name: string;
age: number;
email: string;
}
const USERS_DATA: User[] = [
{ name: 'John', age: 25, email: 'john@example.com' },
{ name: 'Jane', age: 30, email: 'jane@example.com' },
{ name: 'Bob', age: 20, email: 'bob@example.com' },
];
@Component({
selector: 'app-user-table',
templateUrl: './user-table.component.html',
styleUrls: ['./user-table.component.css']
})
export class UserTableComponent implements OnInit {
dataSource = new MatTableDataSource(USERS_DATA);
displayedColumns: string[] = ['name', 'age', 'email'];
ngOnInit() {
this.dataSource.sortingDataAccessor = (item, property) => {
switch (property) {
case 'name': return item.name;
case 'age': return item.age;
case 'email': return item.email;
default: return '';
}
};
}
}
组件来显示表格,并使用
和
组件来定义表头和单元格内容。添加matSort
指令来启用排序功能,并使用[matSort]
绑定数据源的排序属性。
Name
{{ user.name }}
Age
{{ user.age }}
Email
{{ user.email }}
这样,你就可以在表格的每一列上点击排序按钮,实现对数据的列排序了。
上一篇:Angular列可见性