I have a parent component with a method that selects a radio box button. Then I want to call this method in the child. How to use the ‘_inputElement’ from the radio button?
<app-parent>
<app-child [radioChange]="callRadio"></app-child>
</app-parent>
<app-child (click)="radioChange()"></app-child>
ParentComponent(){
@ViewChild('radioButton', {static: false}) matRadioButton : MatRadioButton;
callRadio(){
this.service.onRadioChange();
const event = new MouseEvent('click', {bubbles: true});
this.matRadioButton._inputElement.nativeElement.dispatchEvent(event);
}
}
ChildComponent(){
@Input() radioChange;
}
It gives the error ‘Cannot read properties of undefined (reading ‘_inputElement’)’
>Solution :
The matRadioButton variable is undefined at the moment that callRadio() is being called from the child component, which is the cause of the issue you are experiencing. This is due to the parent component’s ViewChild reference to the MatRadioButton not being available until the parent component has gone through all stages of initialization.
To fix this issue, you can use a technique called "output binding" to pass an event from the child component to the parent component when the radio button is clicked. Here is an example of how you could modify your code to use output binding:
In parent component:
<app-parent>
<app-child (radioClick)="callRadio()"></app-child>
</app-parent>
In child component:
<mat-radio-button (click)="onRadioClick()">Radio Button</mat-radio-button>
import { Component, Output, EventEmitter } from '@angular/core';
export class ChildComponent {
@Output() radioClick = new EventEmitter<void>();
onRadioClick() {
this.radioClick.emit();
}
}
This way, when the radio button is clicked in the child component, it emits an event that the parent component can listen to via the (radioClick) output binding. When the parent component receives this event, it can then call its callRadio() method, which should now have access to the matRadioButton reference and can use it to trigger a click event on the radio button.