在Angular Mat-table中,可以通过逐个更新单元格的方式来实现。
首先,在组件的模板文件中,使用Mat-table来展示数据。在单元格中,使用*ngFor指令迭代每个单元格,并绑定一个变量来获取单元格的值。例如:
Name
{{ element.name }}
Age
{{ element.age }}
然后,在组件类中,定义一个数据源和要显示的列,以及更新单元格的方法。例如:
import { Component } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent {
displayedColumns: string[] = ['name', 'age'];
dataSource = new MatTableDataSource([
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 35 }
]);
updateCell(row: any, column: string, newValue: any) {
row[column] = newValue;
}
}
在上述代码中,updateCell方法接受一个行对象、列名和新值作为参数,并更新对应的单元格的值。
最后,在模板中的单元格中添加编辑按钮,并将updateCell方法绑定到按钮的点击事件。例如:
{{ element.name }}
这样,当点击编辑按钮时,对应的单元格的值将被更新为"New Name"。
注意:在实际应用中,可以根据需要来定义和修改updateCell方法,以满足特定的需求。