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?
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">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.