问题可能是由于嵌套接口的属性名无法与MatTable实际要求的数据生成样式相对应。需要在MatTableDataSource中使用属性名称和相关的键名来根据嵌套接口的结构手动映射数据对象的属性。以下是解决的示例代码:
// 假设嵌套接口名称为'NestedInterface',具有属性'type'和'value' interface NestedInterface { type: string; value: number; }
// 假设主接口是'MainInterface',它有一个与嵌套接口 // 对象相对应的属性'innerObj',用于存储嵌套接口数据 interface MainInterface { name: string; innerObj: NestedInterface; }
@Component(...) export class MyComponent { displayedColumns: string[] = ['name', 'type', 'value']; data: MainInterface[] = [ { name: 'First Object', innerObj: { type: 'One', value: 1 } }, { name: 'Second Object', innerObj: { type: 'Two', value: 2 } } ];
dataSource = new MatTableDataSource
ngOnInit() { this.dataSource.data = this.data.map(d => { // 为嵌套接口定义一个新的属性'type'和'value' // 并使用键名称映射它们 return Object.assign(d, { type: d.innerObj.type, value: d.innerObj.value }); }); } }
在上面的代码中,我们手动将嵌套接口中的属性“拆箱”到父对象中,这样MatTable可以在表格中正确显示它们。手动创建这个映射对象将确保所有的属性都可以与 MatTable 实际要求的列头对齐,从而避免出现 nul / undefined 类型的列。