首先,在组件的类中使用ViewChild来引用MatTable组件。
import { MatTable } from '@angular/material/table';
@ViewChild(MatTable) table: MatTable
接下来,您可以通过调用MatTable的renderRows方法来强制组件重新渲染表格以更新数据。 this.table.renderRows();
下面是一个完整的示例代码: import { Component, OnInit, ViewChild } from '@angular/core'; import { MatTable } from '@angular/material/table';
@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponentComponent implements OnInit { displayedColumns: string[] = ['position', 'name', 'weight', 'symbol']; dataSource = ELEMENT_DATA;
@ViewChild(MatTable) table: MatTable
constructor() { }
ngOnInit(): void { }
updateTableData() { // Here you can update the data source of the table this.dataSource.push({position: 5, name: 'Hydrogen', weight: 1.0079, symbol: 'H'});
// This will render the updated data on the table
this.table.renderRows();
}
}
请注意,此示例代码假定您已经在组件中定义了要显示在表格中的列和数据。此外,当您更改数据源时,只需调用renderRows方法即可更新表格。