为什么 "mat-table" 报告 "Missing definitions for header, footer, and row; cannot determine which columns should be rendered"?

Why does "mat-table" report "Missing definitions for header, footer, and row; cannot determine which columns should be rendered"?

我想在我的 Angular 9 应用程序中创建一个 mat-table。我试图简化事情。我的 .ts 文件是

export class LatestComponent implements OnInit {

  dataSource: MatTableDataSource<item>;

  constructor(
    private apiService: ApiService
  ) { }

  ngOnInit(): void {
    this.apiService.getLatest().subscribe(items => {
      console.log(items[0]);
      this.dataSource = new MatTableDataSource(items);
    });
  }

}

我的简单 one-column table 是 ...

<mat-table #table [dataSource]="dataSource">
    <ng-container matColumnDef="title">
      <mat-header-cell *matHeaderCellDef> item </mat-header-cell>
      <mat-cell *matCellDef="let item">{{ item.title }}</mat-cell>
    </ng-container>
</mat-table>

我已经验证每个 object 从我的观察者返回的标题中都有一个“标题”属性。但是我仍然收到以下错误

ERROR Error: Missing definitions for header, footer, and row; cannot determine which columns should be rendered.
    Angular 27
    RxJS 5
    Angular 9

我需要添加什么才能让我的 table 渲染?

您需要指定行(<mat-header-row><mat-row>)定义:

<mat-table #table [dataSource]="dataSource">
  <ng-container matColumnDef="title">
    <mat-header-cell *matHeaderCellDef> item </mat-header-cell>
    <mat-cell *matCellDef="let item">{{ item.title }}</mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>

并定义应显示哪些列(displayedColumns 变量):

export class LatestComponent implements OnInit {

  dataSource: MatTableDataSource<item>;
  displayedColumns: string[] = ['title']

  constructor(
    private apiService: ApiService
  ) { }

  ngOnInit(): void {
    this.apiService.getLatest().subscribe(items => {
      console.log(items[0]);
      this.dataSource = new MatTableDataSource(items);
    });
  }

}