此问题可能是由于在某些情况下子组件还没有准备好或呈现时尝试在父组件中访问子组件而引起的。为了解决这个问题,可以使用@ViewChild装饰器来访问子组件,并且必须将ngAfterViewInit()生命周期钩子用作初始化代码的一部分。 以下是一个示例代码段:
子组件代码:
export class ChildComponent implements OnInit {
@Input() data: any;
ngOnInit() {
console.log(this.data);
}
}
父组件代码:
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent, {static: false}) childComponent: ChildComponent;
ngAfterViewInit() {
console.log(this.childComponent);
}
}
请注意,如果子组件的视图初始化在父组件的视图初始化之后进行,则必须将{static:false}选项传递给ViewChild装饰器中。