如何解决@ViewChild 未在 ngAfterViewInit
我在使用 *ngIf 和 @ViewChild 时遇到问题。对于此类其他问题,我尝试了大多数推荐的解决方案,但没有任何效果。
我的 HTML 文件如下:
<div id="main-container" class="page-layout blank p-24" fusePerfectScrollbar fxLayout="column">
<mat-tab-group #tabGroup (selectedTabChange)="onTabChange($event);" fxLayout="row wrap">
<mat-tab label="Some1" *ngIf="arrayNames.includes('Some1')">
<ng-template matTabContent>
<my-table #table></my-table>
</ng-template>
</mat-tab>
<mat-tab label="Some2" *ngIf="arrayNames.includes('Some2')">
<ng-template matTabContent>
<my-table #table></my-table>
</ng-template>
</mat-tab>
<mat-tab label="Some3" *ngIf="arrayNames.includes('Some3')">
<ng-template matTabContent>
<my-table #table></my-table>
</ng-template>
</mat-tab>
</mat-tab-group>
</div>
matTabs = [1,2,3];
@ViewChild('tabGroup',{static: false}) tabGroup: MatTabGroup;
data: Array<SomeEntity> = [];
arrayNames: Array<string> = [];
@ViewChild('table',{ static: false }) table: AnotherComponent;
ngOnInit() {
this.someService.getAll()
.subscribe((result) => {
this.data = result;
for (let d of this.data) {
this.arrayNames.push(d.name);
}
});
}
ngAfterViewInit(): void {
this.selectedTabLabel = this.tabGroup?._tabs?.first.textLabel;
this.TabChangeService.changeTab(this.selectedTabLabel);
this.table.displayMyTable();
}
因为 this.table.displayMyTable(); 不显示任何内容,因为“this.table 未定义”
解决方法
您可以考虑尝试的两件事:
首先:用 setTimeout 包围 this.table
ngAfterViewInit(): void {
this.selectedTabLabel = this.tabGroup?._tabs?.first.textLabel;
this.TabChangeService.changeTab(this.selectedTabLabel);
setTimeout(() => {
this.table.displayMyTable();
})
}
第二次尝试:将 ViewChild 更改为 ViewChildren
@ViewChildren('table') table: QueryList<AnotherComponent>;
您可以尝试使用 html 标签的隐藏属性代替 *ngIf 来解决问题。我认为的问题是 html dom 没有 ngif 元素,因此当您尝试访问 Typescript 文件中的此元素时会出现此错误。 你的代码应该是 -
<mat-tab label="Some1" [hidden]="!arrayNames.includes('Some1')">
<ng-template matTabContent>
<my-table #table></my-table>
</ng-template>
</mat-tab>
<mat-tab label="Some2" [hidden]="!arrayNames.includes('Some2')">
<ng-template matTabContent>
<my-table #table></my-table>
</ng-template>
</mat-tab>
<mat-tab label="Some3" [hidden]="!arrayNames.includes('Some3')">
<ng-template matTabContent>
<my-table #table></my-table>
</ng-template>
</mat-tab>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。