在我的 Angular 应用程序中,我的 @ViewChild 实例无法填充 HTL matSort。
我的组件.ts:
import { MatSort } from '@angular/material';
export class MyClassComponent {
@ViewChild(MatSort) sort: MatSort;
}
ngOnInit() {
console.log(this.sort); // undefined
}
我的组件.html:
<mat-table #table [dataSource]="dataSource" matSort>
.......................................................
.......................................................
</mat-table>
我需要使用 matSort 中的 sortChange,但返回时总是未定义。
最佳答案
它将在 AfterViewInit
中初始化并可用。生命周期钩子(Hook):
export class MyClassComponent implements AfterViewInit {
@ViewChild(MatSort) sort: MatSort;
ngAfterViewInit() {
console.log(this.sort); // MatSort{}
}
}
更多关于生命周期钩子(Hook)的信息在这里:https://angular.io/guide/lifecycle-hooks .
关于angular - @Viewchild 看不到matSort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49311585/