#angular #header #angular9 #mat-table
#angular #заголовок #angular9 #mat-table
Вопрос:
Я хочу создать mat-таблицу в моем приложении Angular 9. Я пытался все упростить. Мой файл .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);
});
}
}
и моя простая таблица с одним столбцом такова…
<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>
Я проверил, что в каждом объекте, который возвращается от моего наблюдателя, есть атрибут «title». Тем не менее, я все еще получаю приведенную ниже ошибку
ERROR Error: Missing definitions for header, footer, and row; cannot determine which columns should be rendered.
Angular 27
RxJS 5
Angular 9
Что мне нужно добавить, чтобы моя таблица отображалась?
Ответ №1:
Вам необходимо указать определения строк ( <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);
});
}
}