Angular 动态无线电控制和 bootstrap 4

Angular dynamic radio control and bootstrap 4

我的动态单选按钮控件有点问题。

发生的事情是我似乎无法维护组,所以当一个单选按钮被选中时,两个按钮都被选中。 Bootstrap 要求存在名称字段,但我不确定 formControlName 是否是 bootstrap 查找的内容。

我尝试添加名称属性但没有成功,并将 FormGroup 移至下一个 div。

这是收音机-component.html

<div class="form-group row" [formGroup]="group">
 <label for="{{field.name}}" class="col-sm-2 col-form-label">{{field.label}}</label>
 <div class="custom-control custom-radio custom-control-inline col-sm-1" *ngFor="let answer of field.options">
  <input type="radio" id="{{answer+field.id}}" [formControlName]="field.name" class="custom-control-input">
  <label class="custom-control-label" for="{{answer+field.id}}">{{answer}}</label>
 </div>
</div>

这是发出的html。

<app-radio _nghost-c4="">
 <div _ngcontent-c4="" class="form-group row ng-valid ng-dirty ng-touched" ng-reflect-form="[object Object]">
  <label _ngcontent-c4="" class="col-sm-2 col-form-label" for="gender">Gender</label><!--bindings={
"ng-reflect-ng-for-of": "Male,Female"}-->
<div _ngcontent-c4="" class="custom-control custom-radio custom-control-inline col-sm-1">
 <input _ngcontent-c4="" class="custom-control-input ng-valid ng-dirty ng-touched" type="radio" ng-reflect-form-control-name="gender" ng-reflect-name="gender" id="radio_0">
 <label _ngcontent-c4="" class="custom-control-label" for="radio_0">Male</label>
  </div>
  <div _ngcontent-c4="" class="custom-control custom-radio custom-control-inline col-sm-1">
  <input _ngcontent-c4="" class="custom-control-input ng-valid ng-dirty ng-touched" type="radio" ng-reflect-form-control-name="gender" ng-reflect-name="gender" id="radio_1">
  <label _ngcontent-c4="" class="custom-control-label" for="radio_1">Female</label>
  </div>
 </div>
</app-radio>

编辑:我正在改写我的回答。

您的单选按钮需要有 value 指令,该指令需要绑定到可能的选择项,如下所示:

<input type="radio" value="male" name="gender" [ngModel]="user.gender" > Male
<input type="radio" value="female" name="gender" [ngModel]="user.gender" > Female

name用于分组 value 用于选择单选按钮,并使用 ngModel

更新模型