取消选择并以角度10切换单选按钮

时间:2020-11-11 11:33:43

标签: javascript html angular radio-button

我有3个单选按钮,如下所示。我想选择和取消选择每个单选按钮。而且一次只能激活一个单选按钮。

<div>
  <input type="radio" name="colors" (click)="color='lightgreen'" [(ngModel)]="color">Green
  <input type="radio" name="colors" (click)="color='yellow'" [(ngModel)]="color">Yellow
  <input type="radio" name="colors" (click)="color='cyan'" [(ngModel)]="color">Cyan
</div>
@Component({
  selector: 'app-color',
  templateUrl: './color.component.html'
})
export class ColorComponent {
  color: string;
  .........
}

上面的代码不起作用。如果我在[(ngModel)]="color"中使用<input type="radio" ...>,则可以切换该单选按钮。但是选择该单选按钮将被解释为取消选择,并被取消选择。全部三个都使用[(ngModel)]="color"会完全破坏代码。

有人可以解释一下如何完成吗?

编辑:

找到了一种通过引入按钮来取消选择单选按钮的方法。但是切换不起作用。

<div>
  <input type="radio" [(ngModel)]="color" name="colors" value="lightgreen"/>Green
  <input type="radio" [(ngModel)]="color" name="colors" value="yellow"/>Yellow
  <input type="radio" [(ngModel)]="color" name="colors" value="cyan"/>Cyan
  <button type="button" class="btn btn-secondary" (click)="color=''">Reset</button>
</div>

非常感谢。

1 个答案:

答案 0 :(得分:0)

搜索“角形无线电按钮”->第二个链接:)

来自有角度的文档:Using radio buttons with reactive form directives

import {Component} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';

@Component({
  selector: 'example-app',
  template: `
    <form [formGroup]="form">
      <input type="radio" formControlName="food" value="beef" > Beef
      <input type="radio" formControlName="food" value="lamb"> Lamb
      <input type="radio" formControlName="food" value="fish"> Fish
    </form>

    <p>Form value: {{ form.value | json }}</p>  <!-- {food: 'lamb' } -->
  `,
})
export class ReactiveRadioButtonComp {
  form = new FormGroup({
    food: new FormControl('lamb'),
  });
}
相关问题