【问题标题】:Deselect and toggle a radio button in angular 10取消选择并切换角度 10 中的单选按钮
【发布时间】:2021-02-23 09:04:15
【问题描述】:

我有 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;
  .........
}

上面的代码不起作用。如果我在一个&lt;input type="radio" ...&gt; 中使用[(ngModel)]="color",我可以切换那个单选按钮。但是选择该单选按钮会被解释为取消选中,而取消选中则被解释为选中。在所有三个中都有[(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>

非常感谢。

【问题讨论】:

    标签: javascript html angular radio-button


    【解决方案1】:

    搜索“角形单选按钮”-> 第二个链接 :)

    取自 Angular 文档: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'),
      });
    }
    

    【讨论】:

    • 感谢您的回答,但似乎没有帮助。我仍然无法切换单选按钮
    猜你喜欢
    • 1970-01-01
    • 2019-11-17
    • 2012-02-21
    • 1970-01-01
    • 2012-12-09
    • 2011-07-17
    • 2021-10-15
    • 2013-10-01
    • 1970-01-01
    相关资源
    最近更新 更多