在Angular的mat-table
中实现按行分组可以通过自定义数据源和使用*ngFor
指令来完成。以下是一个基本的步骤指南,包括基础概念和相关代码示例:
mat-table
通常使用一个数据源数组来填充表格。*ngFor
指令在模板中循环遍历分组后的数据,并为每个组创建一个可展开/折叠的行。假设我们有一个包含人员信息的数组,我们希望按部门分组:
export interface Person {
name: string;
department: string;
}
const people: Person[] = [
{ name: 'Alice', department: 'HR' },
{ name: 'Bob', department: 'Engineering' },
{ name: 'Charlie', department: 'HR' },
// ...更多人员
];
创建一个函数来按部门分组:
function groupByDepartment(people: Person[]): { [key: string]: Person[] } {
return people.reduce((groups, person) => {
const department = person.department;
if (!groups[department]) {
groups[department] = [];
}
groups[department].push(person);
return groups;
}, {});
}
在组件的HTML模板中使用*ngFor
来遍历分组后的数据,并为每个组添加展开/折叠功能:
<table mat-table [dataSource]="groupedData">
<!-- 部门列 -->
<ng-container matColumnDef="department">
<th mat-header-cell *matHeaderCellDef> Department </th>
<td mat-cell *matCellDef="let group" colspan="2">
{{ group.key }}
<button (click)="toggleGroup(group.key)">
{{ isGroupExpanded(group.key) ? 'Collapse' : 'Expand' }}
</button>
</td>
</ng-container>
<!-- 姓名列 -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let person" *ngIf="isGroupExpanded(person.department)">
{{ person.name }}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="['department']"></tr>
<tr mat-row *matRowDef="let row; columns: ['name']; when: isGroupVisible"></tr>
</table>
在组件的TypeScript文件中添加逻辑来处理组的展开/折叠状态:
export class TableComponent {
people = people;
groupedData: { key: string, value: Person[] }[] = [];
expandedGroups: Set<string> = new Set();
constructor() {
this.groupedData = Object.entries(groupByDepartment(this.people)).map(([key, value]) => ({ key, value }));
}
toggleGroup(department: string) {
if (this.expandedGroups.has(department)) {
this.expandedGroups.delete(department);
} else {
this.expandedGroups.add(department);
}
}
isGroupExpanded(department: string): boolean {
return this.expandedGroups.has(department);
}
isGroupVisible(row: Person): boolean {
return this.isGroupExpanded(row.department);
}
}
通过上述步骤和代码示例,你可以在Angular的mat-table
中实现按行分组的功能。
领取专属 10元无门槛券
手把手带您无忧上云