【问题标题】:Angular - parent to child component, can't call methodsAngular - 父子组件,不能调用方法
【发布时间】: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.profile in ngAfterViewInit 可能是 undefined。通过console.log 验证它。如果您使用可选链接 (?),则不会出现错误。此外,您只能查看带有ViewChild 的孩子,正如名字已经说过的那样。不是父母。
  • 是的,它返回undefined
  • 你不能从子访问父。你应该通过输出发出方法然后在父监听和实现。
  • 好的,我会尝试的,我是 Angular 新手,我只是在学习。 @VugarAbdullayev
  • 您可以使用@Input 将数据从父母传递给孩子。

标签: angular


【解决方案1】:

没有“正确”的方法,但您可以将方法作为参数传递,如本答案所示

https://stackoverflow.com/a/68983527/3813454

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

@ViewChild 用于从父组件访问子组件,但您做相反的事情。 您应该通过 @Output 在子节点上发出方法,然后在父节点上监听并实现。

    // child component
    @Output() dataTest = new EventEmitter<void>();
    
    ngAfterViewInit(): void {
      this.dateTest.emit();
    }
    // parent html
    
    <child (dataTest)= "onDataTest()> </child>
    // parent ts
    
    public onDataTest(): void {
    // some stuff
    }

【讨论】:

    猜你喜欢
    • 2020-10-20
    • 2023-01-08
    • 2016-12-22
    • 1970-01-01
    • 2017-09-05
    • 2017-12-15
    • 2018-09-12
    • 2017-07-12
    相关资源
    最近更新 更多