在Angular 6中,@ViewChild在延迟加载模块中无法正常工作的问题通常是因为模块尚未完全加载完成就尝试访问视图子组件。
要解决这个问题,可以使用ngAfterViewInit生命周期钩子函数来确保在视图完全加载之后再访问@ViewChild。
以下是一个示例代码,展示了如何使用ngAfterViewInit解决该问题:
// parent.component.html
// parent.component.ts
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
@ViewChild('childComponent', {static: false}) childComponent: ChildComponent;
ngAfterViewInit() {
// 在视图完全加载之后访问子组件
console.log(this.childComponent);
}
}
请注意,我们在@ViewChild装饰器中使用了{static: false}
参数,这是因为在Angular 8之后,默认情况下,@ViewChild将在静态查询中使用,这意味着在ngOnInit期间就会尝试获取子组件引用,这可能会导致延迟加载模块中的问题。通过将{static: false}
参数设置为false,我们告诉Angular在动态查询中使用@ViewChild,这样它就会在ngAfterViewInit期间进行查询。
这样,当父组件的视图完全加载之后,就可以访问子组件了。