基于数据条件为Angular mat-table实现动态列自适应扩展
Angular Material 动态可扩展表格实现方案
现有代码的基础问题修正
在实现动态列之前,先修复现有代码里几个会导致渲染异常的问题:
- 字段拼写笔误:原代码里的
elemente为多余字符,实际取值对象为element - DOM结构不合法:原代码在
ng-container中、td标签外层嵌套div会破坏mat-table的原生表格结构,导致样式错乱,如需布局直接在td标签上添加指令即可 - 字段大小写不匹配:接口返回的实际字段为
clientId、Foo_Type、Foo_Chain,原代码里的字段名和返回值大小写不一致,会出现取不到值的空单元格
动态列核心实现逻辑
核心思路为提前计算所有数据行中Foo_Chain的最大节点长度,动态生成对应数量的列定义,最后将固定基础列和动态生成的列拼接为最终渲染的displayedColumns数组,无需硬编码固定列。
组件类(.ts)逻辑
import { Component, OnInit } from '@angular/core'; import { MatTableDataSource } from '@angular/material/table'; // 匹配接口返回的数据结构 interface FooChainNode { Imported: boolean; Foo: string; } interface TableRow { clientId: string; Foo_Type: string; Foo_Chain: FooChainNode[]; } @Component({ selector: 'app-foo-dynamic-table', templateUrl: './foo-dynamic-table.component.html' }) export class FooDynamicTableComponent implements OnInit { dataSource = new MatTableDataSource<TableRow>([]); displayedColumns: string[] = []; ngOnInit() { // 替换为实际接口返回的数据集 const rawData: TableRow[] = [ {"clientId":"44","Foo_Type":"XYZ","Foo_Chain":[{"Imported":true,"Foo":"XYZ 1"},{"Imported":true,"Foo":"XYZ 2"}]}, {"clientId":"44","Foo_Type":"ABC","Foo_Chain":[{"Imported":true,"Foo":"ABC 1"},{"Imported":true,"Foo":"ABC 2"}]}, {"clientId":"44","Foo_Type":"ASR","Foo_Chain":[{"Imported":true,"Foo":"ASR 1"},{"Imported":true,"Foo":"ASR 2"},{"Imported":true,"Foo":"ASR 3"}]}, {"clientId":"44","Foo_Type":"LOP","Foo_Chain":[{"Imported":true,"Foo":"LOP 1"},{"Imported":true,"Foo":"LOP 2"},{"Imported":true,"Foo":"LOP 3"},{"Imported":true,"Foo":"LOP 4"}]} ]; this.dataSource.data = rawData; // 计算所有行的Foo_Chain最大长度,至少保留2个基础Foo列 const maxFooChainLength = Math.max( ...rawData.map(item => item.Foo_Chain.length), 2 ); // 拼接最终列:固定两列 + 动态生成的Foo列 const dynamicFooCols = Array.from( {length: maxFooChainLength}, (_, index) => `foo_${index + 1}` ); this.displayedColumns = ['clientId', 'fooType', ...dynamicFooCols]; } // 封装单元格取值逻辑,加空值兜底防止控制台报错 getFooValue(row: TableRow, colIndex: number): string { return row.Foo_Chain[colIndex]?.Foo ?? '--'; } }
模板(.html)实现
利用*ngFor批量生成动态列的matColumnDef,无需为每一个Foo列单独写重复的列定义代码:
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <!-- 固定基础列:ClientId --> <ng-container matColumnDef="clientId"> <th mat-header-cell *matHeaderCellDef> {{'ClientId' | uppercase}} </th> <td mat-cell *matCellDef="let element" class="data-column">{{element.clientId}}</td> </ng-container> <!-- 固定基础列:Foo_Type --> <ng-container matColumnDef="fooType"> <th mat-header-cell *matHeaderCellDef> {{'Foo_Type' | uppercase}} </th> <td mat-cell *matCellDef="let element" class="data-column">{{element.Foo_Type}}</td> </ng-container> <!-- 批量生成动态Foo列定义 --> <ng-container *ngFor="let colName of displayedColumns; let colIndex = index"> <ng-container *ngIf="colName.startsWith('foo_')" [matColumnDef]="colName"> <th mat-header-cell *matHeaderCellDef> {{'Foo ' + (colIndex - 1) | uppercase}} </th> <td mat-cell *matCellDef="let element" class="data-column"> {{ getFooValue(element, colIndex - 2) }} </td> </ng-container> </ng-container> <!-- 表头和行渲染定义 --> <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table>
匹配需求的实现效果
- 基础渲染默认保留4个列:
ClientId | Foo_Type | Foo 1 | Foo 2,满足基础列要求 - 当数据集中某条记录的
Foo_Chain节点数超过2个时,自动追加对应数量的列,比如出现3个节点就追加Foo 3、出现4个节点就追加Foo 4 - 短节点的行在扩展列位置自动显示兜底占位符,不会出现空单元格报错
内容的提问来源于stack exchange,提问作者Ravel Sbrissa Okada
相关产品推荐
相关产品推荐

