Angular中如何展示或遍历嵌套数组(含数组的数组)
Angular Material Table 按日期分组展示嵌套数组数据
实现步骤
1. 组件定义与数据处理
在组件中定义数据接口和模拟数据,保证类型安全:
import { Component } from '@angular/core'; // 定义活动数据接口 interface Activity { date: string; User: string; Action: string; } @Component({ selector: 'app-date-grouped-table', templateUrl: './date-grouped-table.component.html', styleUrls: ['./date-grouped-table.component.css'] }) export class DateGroupedTableComponent { // 模拟嵌套数组数据 activityGroups: Activity[][] = [ [ { "date": "September 11", "User": "ABC", "Action": "Added" }, { "date": "September 11", "User": "asd", "Action": "Removed" } ], [ { "date": "September 8", "User": "sdf", "Action": "Added" }, { "date": "September 8", "User": "rty", "Action": "Updated" }, { "date": "September 8", "User": "pol", "Action": "Removed" } ] ]; }
2. HTML模板实现
通过*ngFor循环外层数组,每个子数组对应一个日期分组,分组上方显示日期,下方用Mat Table展示该组的记录:
<div class="activity-container"> <!-- 循环每个日期分组 --> <div *ngFor="let group of activityGroups" class="date-group"> <!-- 日期标题 --> <p class="date-title">{{ group[0].date }}</p> <!-- Mat Table 展示该组记录 --> <table mat-table [dataSource]="group" class="activity-table"> <!-- 用户列定义 --> <ng-container matColumnDef="User"> <td mat-cell *matCellDef="let item"> {{ item.User }} </td> </ng-container> <!-- 操作列定义 --> <ng-container matColumnDef="Action"> <td mat-cell *matCellDef="let item"> {{ item.Action }} </td> </ng-container> <!-- 数据行 --> <tr mat-row *matRowDef="let row; columns: ['User', 'Action']"></tr> </table> </div> </div>
3. 样式调整(可选)
添加CSS让表格呈现类似无序列表的视觉效果:
.activity-container { padding: 1rem; } .date-group { margin-bottom: 1.5rem; } .date-title { font-size: 1.2rem; font-weight: 500; margin: 0 0 0.5rem 0; } .activity-table { border-collapse: separate; border-spacing: 1.5rem 0; } .activity-table mat-row { display: flex; gap: 1.5rem; }
效果说明
上述代码会按日期分组展示数据,每个日期下方用Mat Table呈现对应的用户操作记录,视觉效果与你期望的格式一致,同时复用了Angular Material Table的组件能力。
内容的提问来源于stack exchange,提问作者user3933327
相关产品推荐
相关产品推荐

