0

I want to call function from parent component for get some datas but I can't. Not getting any error but it returns undefined. Where am I wrong?

parent.component

      user:any

      dataTest(){
        console.log(this.user);
      }

child.component

    @ViewChild(AppLayoutComponent) profile!: AppLayoutComponent;
    ngAfterViewInit():void{
        this.profile?.dataTest()
      }
JsNgian
  • 795
  • 5
  • 19
vega9231w
  • 31
  • 1
  • 9

2 Answers2

0

@ViewChild is for accessing child component from parent but you do opposite. You should emit method on child via @Output then on parent listen and implement.

    // 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
    }
JsNgian
  • 795
  • 5
  • 19
Vugar Abdullayev
  • 1,852
  • 3
  • 21
  • 46
0

There is no "right" way, but you can pass the method as a parameter as shown in this answer

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

Eduardo
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 14 '21 at 13:27