简体   繁体   English

当我将检查应用于单选按钮时如何触发点击事件?

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

I have an uninitialized property in app.component.ts :我在app.component.ts有一个未初始化的属性:

color!:string;

I want color to be automatically initialized when I set checked to a radio button:当我将checked的选项设置为单选按钮时,我希望自动初始化color

<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.不幸的是, checked不会触发 click 事件,因此color仍未初始化。 Any idea to solve it?有什么办法解决吗?

Use input() :使用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 :或者您可以使用ngModel

<input type="radio" name="colors" value="red" [(ngModel)]="color">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM