要解决"Angular 8 - Material 表格删除后未正确显示数据"问题,可以尝试以下解决方法:
splice
方法或filter
方法来删除数据项。确保在删除后更新数据源。// 示例代码
deleteItem(item: any) {
const index = this.dataSource.indexOf(item);
if (index >= 0) {
this.dataSource.splice(index, 1);
this.dataSource = [...this.dataSource]; // 更新数据源
}
}
// 示例代码
import { ChangeDetectorRef } from '@angular/core';
constructor(private cdRef: ChangeDetectorRef) {}
deleteItem(item: any) {
const index = this.dataSource.indexOf(item);
if (index >= 0) {
this.dataSource.splice(index, 1);
this.cdRef.detectChanges(); // 手动触发变更检测
}
}
// 示例代码
import { MatTableDataSource } from '@angular/material';
dataSource = new MatTableDataSource([]);
deleteItem(item: any) {
const index = this.dataSource.data.indexOf(item);
if (index >= 0) {
this.dataSource.data.splice(index, 1);
this.dataSource.data = [...this.dataSource.data]; // 更新 MatTable 数据源
}
}
通过以上方法,你应该能够正确删除数据项后更新表格。记得根据你自己的代码结构和使用的组件进行相应的调整。