angular - 将动态列添加到 mat-table 并单击内联更改列标题
问题描述
我尝试在单击按钮时构建材料表,我可以添加/删除列和表行。我尝试添加
displayedColumns: string[] = ['name', 'weight', 'symbol', 'position'];
columnsToDisplay: string[] = this.displayedColumns.slice();
data: PeriodicElement[] = ELEMENT_DATA;
addColumn() {
const randomColumn = Math.floor(Math.random() * this.displayedColumns.length);
this.columnsToDisplay.push(this.displayedColumns[randomColumn]);
}
removeColumn() {
if (this.columnsToDisplay.length) {
this.columnsToDisplay.pop();
}
这是堆栈闪电战
我得到了添加/删除列,但我无法进行内联编辑。有什么办法可以让它工作吗?
谢谢
解决方案
当您单击该单元格时,一种可能的解决方案是显示输入而不是单元格的标签。然后通过使用 ngModel 指令 ( https://angular.io/api/forms/NgModel ),您将输入的值直接绑定到 ELEMENT_DATA 数组,使您可以看到直接反映在表上的更改。
在你的 component.html
<table mat-table [dataSource]="data" class="mat-elevation-z8">
<ng-container [matColumnDef]="column"
*ngFor="let column of displayedColumns; let columnIndex = index;">
<th mat-header-cell *matHeaderCellDef> {{column}} </th>
<td mat-cell *matCellDef="let element">
<span (click)="onEdit(element.position, columnIndex)"
*ngIf="!cellEditting(element.position, columnIndex)">
{{element[column]}}
</span>
<input type="text" [(ngModel)]="data[element.position -1 ][column]"
*ngIf="cellEditting(element.position, columnIndex)">
<button type="button" *ngIf="cellEditting(element.position, columnIndex)"
(click)="onClose(element.position, column)" >Close</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
<tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
</table>
在你的 component.ts
//will keep track of the cell currently being editted
edittedCell = { row: -1, column: -1 };
onEdit(row: number, column: number) {
this.edittedCell = { row, column };
}
cellEditting(row: number, column: number): boolean {
return column === this.edittedCell.column && row === this.edittedCell.row;
}
onClose(row: number, column: string, input) {
this.edittedCell = {row: -1, column: -1}
}
推荐阅读
- laravel - 在注册应用服务提供商中访问身份验证用户的问题
- python - add_widget 缺少 1 个必需的位置参数:“screen”还有参数“screen”未完成
- python - 创建了站点地图,但 Google 无法获取错误
- react-native-android - 如何使用 onPress 功能选择平面列表项目并突出显示 react-native 中的项目?
- linux - 用 read() 系统调用覆盖 Shellcode?
- python - 在每个拆分上运行一个循环
- python - 每次交货多次取货,但无法找到部分解决方案
- viewer - 如何从 table1 包中查看查看器
- flutter - 复杂的渐变
- vb.net - 即使 MSL 在资源中,如何在运行时在 EF 模型的概念信息和存储信息之间进行转换?