我的 mat-table 工作正常,但是在按照官方 api 文档添加 mat-sort 时,它在 ngAfterViewInit 失败并显示以下消息
无法在 ViewFeedbackComponent.ngAfterViewInit 处设置未定义的属性“排序”
已经有一个关于这个问题的帖子(见下面的链接)Mat-table Sorting Demo not working,但我仍然无法让它工作。
有人发现问题了吗?官方示例使用组件本身中定义的“静态”MatTableDataSource,但是我从后端查询。
任何帮助是极大的赞赏!
MatSortModule 已经在 app.module.ts 中导入,mat-sort-header 指令应用于列,并且 ngAfterViewInit 已经与官方示例中的完全一样......
import { Component, OnInit, ViewEncapsulation, ViewChild, AfterViewInit} from '@angular/core';
import { Feedback} from '../../../../../models/feedback';
import { FeedbackService} from '../../services/feedback.service';
import { MatTableDataSource, MatSort} from '@angular/material';
@Component({
selector: 'app-view-feedback',
templateUrl: './view-feedback.component.html',
styleUrls: ['./view-feedback.component.css'],
encapsulation: ViewEncapsulation.Emulated
})
export class ViewFeedbackComponent implements OnInit, AfterViewInit {
feedbacks: Feedback[] = [];
showSpinner: boolean = true;
displayedColumns: String[] = [
'id',
'user',
'timestamp',
'stars'
];
dataSource: MatTableDataSource < Feedback > ;
@ViewChild(MatSort) sort: MatSort;
constructor(private _feedbackService: FeedbackService) {}
ngOnInit() {
this._feedbackService.getFeedback.subscribe(
res => {
this.feedbacks = res;
this.dataSource = new MatTableDataSource(this.feedbacks);
}
);
}
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
}
<div class="mat-tbl-container mat-elevation-z8">
<mat-table #tbl [dataSource]="dataSource" matSort>
<!-- column definitions -->
<ng-container matColumnDef="id">
<mat-header-cell *matHeaderCellDef mat-sort-header>Id</mat-header-cell>
<mat-cell *matCellDef="let r"> {{r._id}} </mat-cell>
</ng-container>
<ng-container matColumnDef="user">
<mat-header-cell *matHeaderCellDef mat-sort-header>User Id</mat-header-cell>
<mat-cell *matCellDef="let r"> {{r.user}} </mat-cell>
</ng-container>
<ng-container matColumnDef="timestamp">
<mat-header-cell *matHeaderCellDef mat-sort-header>Date</mat-header-cell>
<mat-cell *matCellDef="let r"> {{r.timestamp}} </mat-cell>
</ng-container>
<ng-container matColumnDef="stars">
<mat-header-cell *matHeaderCellDef mat-sort-header>Stars</mat-header-cell>
<mat-cell *matCellDef="let r"> {{r.stars}} </mat-cell>
</ng-container>
<!-- tbl display settings -->
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>