【发布时间】:2021-09-14 13:09:36
【问题描述】:
我想从父组件调用函数来获取一些数据,但我不能。没有收到任何错误,但它返回未定义。我哪里错了?
parent.component
user:any
dataTest(){
console.log(this.user);
}
child.component
@ViewChild(AppLayoutComponent) profile!: AppLayoutComponent;
ngAfterViewInit():void{
this.profile?.dataTest()
}
【问题讨论】:
-
this.profileinngAfterViewInit可能是undefined。通过console.log验证它。如果您使用可选链接 (?),则不会出现错误。此外,您只能查看带有ViewChild的孩子,正如名字已经说过的那样。不是父母。 -
是的,它返回
undefined。 -
你不能从子访问父。你应该通过输出发出方法然后在父监听和实现。
-
好的,我会尝试的,我是 Angular 新手,我只是在学习。 @VugarAbdullayev
-
您可以使用
@Input将数据从父母传递给孩子。
标签: angular