【问题标题】:Two way binding not working in ng-bootstrap radio button in an angular reactive form两种方式绑定在角度反应形式的 ng-bootstrap 单选按钮中不起作用
【发布时间】:2018-03-28 19:26:55
【问题描述】:

我正在使用 Angular 4、Bootstrap 4 和 ngbootstrap 开发应用程序。 html代码 -

<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 获取请求并获取 isRequired 字段的值。如果获取成功,我会调用以下方法来设置单选按钮的值。

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

问题 - 让我们假设 isRequired = true 的值。这个值 正确获取并使用此值初始化无线电 在表单加载。但是,如果用户更改值(isRequired = 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>

我做错了什么?

【问题讨论】:

标签: twitter-bootstrap angular bootstrap-4 ng-bootstrap angular-reactive-forms


【解决方案1】:

根据The data model and the form model 响应式表单指南

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 buttons 中所述。

【讨论】:

  • this.variable 是从数据库中获取的对象,它包含单选按钮的初始值。保存表单后,我正在检查 myForm.value.isRequired。
  • ngModel 和 formControlName 可以一起使用吗?
【解决方案2】:

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

请阅读here提供的文档。

【讨论】:

    猜你喜欢
    • 2021-07-03
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2019-05-13
    • 2017-02-20
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多