要解决Angular mat-table在添加新行后不刷新的问题,您可以尝试以下方法:
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
data: any[] = [];
constructor(private cdr: ChangeDetectorRef) { }
ngOnInit() {
}
addNewRow() {
// 添加新行的逻辑
// ...
// 手动触发变更检测
this.cdr.detectChanges();
}
}
import { Component, OnInit, NgZone } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
data: any[] = [];
constructor(private ngZone: NgZone) { }
ngOnInit() {
}
addNewRow() {
// 添加新行的逻辑
// ...
// 在NgZone之外的上下文中运行变更检测
this.ngZone.runOutsideAngular(() => {
// 手动触发变更检测
this.ngZone.run(() => {});
});
}
}
使用ChangeDetectorRef或NgZone中的任何一个方法都可以手动触发变更检测,从而更新mat-table的数据。这将确保添加新行后表格能够正确地刷新并显示新行。