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

Time:08-22

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?

CodePudding user response:

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">
  • Related