Search code examples
angularparent-childinitializerviewchildangular13

@ViewChild - initializer error on Angular 13


I am creating app in Angular 13. I want to call the method show() of ChildComponent from ParentComponent, using @ViewChild, but I get errors. The older questions and answers are not working in this case.

Parent:

<app-child #child></app-child>
@ViewChild('child') child: ChildComponent;

showChild() {
   this.child.show();
}

Child:

show(){
  console.log('show');
}

Error:

Property 'child' has no initializer and is not definitely assigned in the constructor.


Solution 1:

Parent:

@ViewChild('child') child!: ChildComponent;

Error:

TypeError: Cannot read properties of undefined (reading 'show')


Solution 2:

Parent:

@ViewChild('child') child: ChildComponent = new ChildComponent;

Without errors Works fine but I have doubts if this is correct?


Solution

  • you can initialize like that. Ii will help you to resolvee your error.

    @ViewChild('child') child: ChildComponent = {} as ElementRef;
    
    or 
    
    @ViewChild('child') child: ChildComponent = {} as ChildComponent;