我有一个带有单选按钮的响应式(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。在这里你可以看到名称基本相同。不过,由于某些奇怪的原因,两个复选框都可以被选中...
最佳答案
您必须为您的 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);
}
}
结果
关于angular - react 形式 : Radio button selects both,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48224772/