Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@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?

like image 462
Weronika Avatar asked Nov 04 '25 07:11

Weronika


1 Answers

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;
like image 122
Sunny Avatar answered Nov 05 '25 22:11

Sunny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!