Home > Enterprise >  Angular 14 calling Child Component method from Parent Component
Angular 14 calling Child Component method from Parent Component

Time:01-07

I am getting an error when I try to call a childComponent method from the Parent

**Child TS. **

   export class ChildComponent implements OnInit {
     ChildMethod(){
       console.log('test');
     }
     constructor() { }
   }

**Parent Ts **

   @ViewChild(ChildComponent , {static : false}) child!:ChildComponent ;
  
   CallChild(){
       this.child.ChildMethod();
     }

when I call CallChild I get this error Cannot read properties of undefined (reading 'ChildMethod') at GpmainComponent.CallChild (gpmain.component.ts:39:16)

CodePudding user response:

Try to declare your Child component in constructor.

in Parent.ts:

constructor(private child: ChildComponent) {}

CallChild() {
  this.child.ChildMethod();
}

CodePudding user response:

It could possibly depend on when you are calling CallChild.

If you're calling it before the view has been rendered, then this.child will be undefined, thus causing the error

CodePudding user response:

This is related to static: false and timing.

When set to false, the ViewChild query will be resolved after change detection runs and right before ngAfterViewInit. This means that if you attempt to call in in ngOnInit for example then child will be undefined.

You have 2 options:

  • Try calling it later, after change detection runs and when it's initialized
  • Set static: true if the child is not under an *ngIf and then it will be resolved sooner and available in ngOnInit
  • Related