angular - react 形式 : Radio button selects both

标签 angular angular-reactive-forms

我有一个带有单选按钮的响应式(Reactive)表单。单选按钮看起来像这样:

  <label [for]="question.id + '_' + selectableValue.id"
    *ngFor="let selectableValue of selectableValues">
    <input
      type="radio"
      [id]="question.id + '_' + selectableValue.id"
      [value]="selectableValue.id"
      [formControl]="formControlToUse"
      [formControlName]="question.id"
      name="{{ question.id }}"
      (change)="execChange($event)"
    >
    {{selectableValue.displayName}}
  </label>

所有变量都存在并正确解析。 question.id 每个问题都是唯一的(一个问题由多个 radio 组成(= 可选值)。

但是,当我单击一个单选按钮时,另一个没有取消选中-> 两个都被选中。但是: radio 中的名称相同。

有人能帮帮我吗?

@更新: 请在此处查看生成的 DOM。在这里你可以看到名称基本相同。不过,由于某些奇怪的原因,两个复选框都可以被选中...

enter image description here

最佳答案

您必须为您的 radio 组提供相同的 formControlName。您可以删除 name 属性,因为您使用 formControlName

完整示例:

@Component({
    selector: 'app',
    template: `
        <div [formGroup]="form">
            <div *ngFor="let question of questions">
                <label [for]="question.id + '_' + selectableValue.id" *ngFor="let selectableValue of selectableValues">
                    <input type="radio"
                           [id]="question.id + '_' + selectableValue.id"
                           [value]="selectableValue.id"
                           [formControlName]="question.id">
                    {{selectableValue.displayName}}
                </label>
            </div>
        </div>
    `,
})
export class AppCp {
    form: FormGroup;
    questions = [{id: 'id1'}, {id: 'id2'}];
    selectableValues = [
        {id: 1, displayName: 'first'},
        {id: 2, displayName: 'second'}
    ];

    constructor(fb: FormBuilder) {
        let group = {};
        this.questions.forEach(q => group[q.id] = '');
        this.form = fb.group(group);
    }
}

结果

enter image description here

关于angular - react 形式 : Radio button selects both,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48224772/

相关文章:

angular - 如何在 Angular 的 Reactive Forms 中设置值以形成控件

forms - 在 Angular 4 中,为什么异步验证的嵌套控件不会将其有效性传播到父 FormGroup?

angular - ngrx中的多个商店

angular - 在 Angular 4 Reactive Forms 中提交时显示验证消息

导入 mat-checkbox 时出现 Angular Material 错误

javascript - 我们可以将 Angular FormArray 与 angular2-multiselect 下拉菜单一起使用吗?

typescript - 尝试在模板中使用组件函数时出现错误 "TypeError: ... is not a function"

angular - 在 APP_INITIALIZATION 之后使用已解析的配置提供 InjectionToken

angular - 如何使用 labelPosition ="bottom"更改 Material 步进线样式

javascript - Angular Reactive formArray 中的单选按钮 - 选择数组中的一项