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.
Parent:
@ViewChild('child') child!: ChildComponent;
Error:
TypeError: Cannot read properties of undefined (reading 'show')
Parent:
@ViewChild('child') child: ChildComponent = new ChildComponent;
Without errors Works fine but I have doubts if this is correct?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With