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()
      }
5
  • this.profile in ngAfterViewInit is maybe undefined. Validate it via console.log. You get no error if you use optional chaining (?). Also you can only view childs with ViewChild as the name already says. Not parents. Commented Sep 14, 2021 at 13:13
  • yes, it returns undefined. Commented Sep 14, 2021 at 13:14
  • you cannot access parent from child.You should emit method via Output then on parent listen and implement. Commented Sep 14, 2021 at 13:14
  • okay, i will try, im new in angular, im just learning. @VugarAbdullayev Commented Sep 14, 2021 at 13:15
  • you can use @Input for pass data from parent to child. Commented Sep 14, 2021 at 13:19

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.