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

How to trigger click event when I apply checked to a radio button?

I have an uninitialized property in app.component.ts:

color!:string;

I want color to be automatically initialized when I set checked to a radio button:

<div>
  <input type="radio" name="colors" (click)="color='red'" checked>Red
  <input type="radio" name="colors" (click)="color='blue'">Blue
  <input type="radio" name="colors" (click)="color='green'">Green
</div>

Unfortunately, checked does not trigger the click event so color is still uninitialized. Any idea to solve it?

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 :

Use input():

<input type="radio" name="colors" value="red" (input)="onInput($event)">Red
<input type="radio" name="colors" value="blue" (input)="onInput($event)">Blue
<input type="radio" name="colors" value="green" (input)="onInput($event)">Green
onInput(event: Event) {
  this.color = event.target.value;
}

Or you can use ngModel:

<input type="radio" name="colors" value="red" [(ngModel)]="color">
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