如何通过添加行动态刷新Angular Material表格?
解决Angular Material表格无法添加新行的问题
问题排查与修复步骤
1. 修复对象语法错误
refresh方法里创建对象时,nom属性的字符串未闭合引号,会导致代码报错:
// 错误写法 const pjFinal = { libelle: 'testLibelle', nom: 'testNom }; // 修正后 const pjFinal = { libelle: 'testLibelle', nom: 'testNom' };
2. 定义表格列配置数组
模板中使用的displayedColumnsJustifs未在TS中定义,Angular无法识别要渲染的列,需在组件类中添加:
public displayedColumnsJustifs = ['libelle', 'nomDocument'];
3. 添加表格数据行模板
你的Material表格仅定义了表头行,缺少数据行渲染模板,这是表格显示数据的核心部分,必须补充:
<tr mat-row *matRowDef="let row; columns: displayedColumnsJustifs;"></tr>
4. 优化数据源更新方式(可选)
每次创建新的MatTableDataSource不是最优方案,可直接更新现有数据源的data属性触发视图更新:
public refresh(): void { const pjFinal = { libelle: 'testLibelle', nom: 'testNom' }; this.piecesJointes.push(pjFinal); this.dataSource.data = this.piecesJointes; }
修正后的完整代码
TS代码
import { Component } from '@angular/core'; import { MatTableDataSource } from '@angular/material/table'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent { public piecesJointes: any[] = []; public dataSource = new MatTableDataSource(this.piecesJointes); public displayedColumnsJustifs = ['libelle', 'nomDocument']; public refresh(): void { const pjFinal = { libelle: 'testLibelle', nom: 'testNom' }; this.piecesJointes.push(pjFinal); this.dataSource.data = this.piecesJointes; console.log(this.dataSource); } }
HTML代码
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8 demo-table" > <!-- libelle Column --> <ng-container matColumnDef="libelle"> <th mat-header-cell *matHeaderCellDef> column1 </th> <td mat-cell *matCellDef="let element">{{ element.libelle }}</td> </ng-container> <!-- nom doc Column --> <ng-container matColumnDef="nomDocument"> <th mat-header-cell *matHeaderCellDef> column2 </th> <td mat-cell *matCellDef="let element">{{ element.nom }}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumnsJustifs"></tr> <!-- 新增数据行模板 --> <tr mat-row *matRowDef="let row; columns: displayedColumnsJustifs;"></tr> </table> <!-- 触发refresh的文件选择组件 --> <input type="file" (fileSelected)="refresh()" />
内容的提问来源于stack exchange,提问作者Olivier
相关产品推荐
相关产品推荐

