双向绑定在角反应形式的 ng-bootstrap 单选按钮中不起作用



我正在开发一个带有Angular 4,Bootstrap 4和ngbootstrap的应用程序。网页代码 -

<div class="container">
  <form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value)">
    <div class="form-group">
      <div class="row">
        <legend class="col-form-legend col-sm-2">Required</legend>
        <div class="btn-group col-sm-2" ngbRadioGroup name="isRequired" formControlName="isRequired">
          <label ngbButtonLabel class="btn-primary">
            <input ngbButton type="radio" name="radio" [value]="true">Yes
          </label>
          <label ngbButtonLabel class="btn-primary">
            <input ngbButton type="radio" name="radio" [value]="false">No
          </label>
        </div>
      </div>
    </div>
    <div class="form-group row">
      <div class="col-sm-6">
        <button type="submit" class="btn btn-info">
          <i class="fa fa-floppy-o fa-lg"></i>
          Save
        </button>
      </div>
    </div>  
  </form>
</div>

控制器

 private buildForm() {
    this.myForm = this.formBuilder.group({
      isRequired: [],
    });
  }

在控制器的 ngOnInit(( 钩子中,我调用 buildForm(( 方法。然后我发出一个 Http get 请求并为 isRequired 字段获取一个值。如果获取成功,我将调用以下方法来设置单选按钮的值。

private loadFormData() {
    this.myForm.patchValue({
      isRequired: this.variable.isRequired,
    });
}

问题 - 让我们假设值 isRequired = true。此值 正确获取并使用此值初始化无线电 在表单加载时。但是,如果用户更改值 (是必需的 = false(该字段仍保留以前的值(isRequired = true(。

如果我使用以下代码,这工作正常 -

<div class="form-group">
    <div class="row">
      <legend class="col-form-legend col-sm-2">Required</legend>
      <input type="radio" formControlName="isRequired" value="true"> Yes
      <input type="radio" formControlName="isRequired" value="false"> No
    </div>
</div>

我做错了什么?

我意识到这个问题是由波普尔引起的.jsng-bootstrap的官方文档强烈建议不要包含它。

请阅读此处提供的文档。

根据反应式表单的数据模型和表单模型指南

User changes flow from the DOM elements to the form model, not to the data model. The form controls never update the data model.

这意味着当用户从无线电中选择任何值时,您的变量this.variable.isRequired不会更新。要获得表单值,您必须使用this.myForm.value或者您必须在广播中使用ngModel,如ng-bootstrap按钮中所述。

最新更新