在依赖模型驱动形式的同时预先填充ng-bootstrap的预先输出的问题

时间:2016-12-29 18:53:06

标签: angular angular2-forms ng-bootstrap

假设我有以下模型驱动形式:

this.addressForm = this.formBuilder.group({
  address: this.formBuilder.group({
    placeId: [this.address.placeId],
    description: [this.address.description]
  })
});

以下模板:

<form [formGroup]="addressForm" (ngSubmit)="updateAddress()" novalidate>
  <div class="form-group">
    <div class="input-group">
      <input type="text"
         formControlName="address"
         placeholder="Type in you address"
         [ngbTypeahead]="chooseAddress"
         [inputFormatter]="addressFormatter"
         [resultFormatter]="addressFormatter"
         autocomplete="off"
         class="form-control">
    </div>
   ...
</form>

addressFormatter:

addressFormatter = param => param.description;

假设address是一个包含两个属性的对象:placeIddescription

似乎无法处理formGroup(此处为address)而不是formControl(此处为address.placeId)并且仍然预填充表单中的一个对象的属性(例如address.description)。

我收到以下错误:

  

./UserAccountAddressComponent类中的错误UserAccountAddressComponent - 内联模板:8:9导致:control.registerOnChange不是函数   TypeError:control.registerOnChange不是函数

我无法在字段中显示该对象的一个​​属性(address.description),并在我提交表单(address.placeId)时使用另一个属性,同时仍然能够预填充表单其中一个对象属性(此处为address.description)。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

我猜您的错误意味着与您的输入绑定的组件未实现ControlValueAccessor interface。尝试在输入中添加[formControl]绑定:

<form [formGroup]="addressForm" (ngSubmit)="updateAddress()" novalidate>
  <div class="form-group">
    <div class="input-group">
      <input type="text"
         formControlName="address"
         [formControl]="addressForm.address"
         placeholder="Type in you address"
         [ngbTypeahead]="chooseAddress"
         [inputFormatter]="addressFormatter"
         [resultFormatter]="addressFormatter"
         autocomplete="off"
         class="form-control">
    </div>
   ...
</form>

答案 1 :(得分:0)

问题在于我指定我的反应形式。

改变自:

this.addressForm = this.formBuilder.group({
  address: this.formBuilder.group({
    placeId: [this.address.placeId],
    description: [this.address.description]
  })
});

...为:

this.addressForm = this.formBuilder.group({
  address: this.formBuilder.control({//Notice the control() method instead of group() method
    placeId: this.address.placeId,
    description: this.address.description
  })
});

...允许我为整个输入控件指定一个对象类型而不是字符串类型。请参阅此处的 FormBuilder控件()方法的官方角度文档:https://angular.io/docs/ts/latest/api/forms/index/FormBuilder-class.html#!#control-anchor

编辑:请注意,这与ng bootsrap框架无关。