Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use _inputElement in child component

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’)’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading