在 angular 8 中使用 @viewChild
using @viewChild in angular 8
我有一个使用@ViewChild 的应用程序,下面是我的代码
@ViewChild('paginator', { read: MatPaginator, static: true}) public paginator: MatPaginator;
我用的正面
<mat-paginator [ngStyle]="{'display': orders.length > 0 ? 'flex': 'none' }" #paginator>
我已经实现了 AfterViewInit,这是我用来检查分页器是否已初始化的代码:
ngAfterViewInit(): void {
console.log('tab group', this.paginator);
}
但是 this.tabGroup 未定义,因此我无法将其设置为 属性。我做错了什么。
谢谢
因为 Angular 8 ViewChild
和 ContentChild
装饰器必须有一个名为 static 的新选项。
如果您在动态元素上添加 static: true
(包含在条件或循环中),那么它将无法在 ngOnInit
或 ngAfterViewInit
中访问。
将其设置为 static: false
应该会如您所愿。
此外,当更新到 Angular 8 时,在命令行中会有一条消息解释新的 ViewChild
和 ContentChild
更改,以及 link this documentation page, and here's the pull request 的变化,有一些解释。这可能有助于您了解这些变化。
我有一个使用@ViewChild 的应用程序,下面是我的代码
@ViewChild('paginator', { read: MatPaginator, static: true}) public paginator: MatPaginator;
我用的正面
<mat-paginator [ngStyle]="{'display': orders.length > 0 ? 'flex': 'none' }" #paginator>
我已经实现了 AfterViewInit,这是我用来检查分页器是否已初始化的代码:
ngAfterViewInit(): void {
console.log('tab group', this.paginator);
}
但是 this.tabGroup 未定义,因此我无法将其设置为 属性。我做错了什么。
谢谢
因为 Angular 8 ViewChild
和 ContentChild
装饰器必须有一个名为 static 的新选项。
如果您在动态元素上添加 static: true
(包含在条件或循环中),那么它将无法在 ngOnInit
或 ngAfterViewInit
中访问。
将其设置为 static: false
应该会如您所愿。
此外,当更新到 Angular 8 时,在命令行中会有一条消息解释新的 ViewChild
和 ContentChild
更改,以及 link this documentation page, and here's the pull request 的变化,有一些解释。这可能有助于您了解这些变化。