首先,需要确认在组件中是否正确引入了 MatTableDataSource 和 MatTableModule。然后,检查数据是否正确加载到数据源中。如果数据源中有数据,但数据表仍然没有显示数据,则可以尝试在数据表组件中添加“ChangeDetectorRef”来强制更新组件。代码示例如下:
import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
@Component({
selector: 'app-data-table',
templateUrl: './data-table.component.html',
styleUrls: ['./data-table.component.css']
})
export class DataTableComponent implements OnInit {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = new MatTableDataSource(ELEMENT_DATA);
constructor(private cdr: ChangeDetectorRef) { }
ngOnInit() {
this.dataSource.data = ELEMENT_DATA;
}
ngAfterViewInit() {
this.cdr.detectChanges();
}
}
export interface Element {
name: string;
position: number;
weight: number;
symbol: string;
}
const ELEMENT_DATA: Element[] = [
{position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
// Other data
];