angular 4将包含其他对象的对象传递给FormBuilder.group函数会导致奇怪的表单行为

时间:2017-08-13 22:36:56

标签: angular angular2-forms angular-forms

创建一个由以下"嵌套对象组成的嵌套表单" (建筑物):

export class Building{
  id: number = 0;
  doorsCount: number = 0;
  description: string = '';
  address: Address = new Address();
  buildingType: BuildingType = new BuildingType();
}

export class Address{
  id: number = 0;
  description: string = '';
}

export class BuildingType{
  id: number = 0;
  description: string = '';
}

正如您所看到的,Building类包含其他类,如Address和BuildingType,它们还具有其他属性,如id和description。

创建表单时,我在组件ts文件中使用了以下代码:

buildingForm: FormGroup;

construct(private fb: FormBuilder){
 this.buildingForm = this.createBuildingFG(new Building);
}

createBuildingFG(building: Building){
  let formGroup : FormGroup;
  formGroup = this.fb.group(building);

  // Because object of type "building" contain properties of non-primitive 
  // types such as object Address and BuildingType I think the following 
  // additional lines are required. 

  formGroup.controls.address = this.fb.group(building.address);
  formGroup.controls.buildingType = this.fb.group(building.buildingType);

  return formGroup;
}

这就是表单绑定到HTML模板的方式:

<form [formGroup]="buildingForm">
    <label>
        Door count: 
        <input formControlName="doorsCount" >
    </label>
    <label>
        Building description: 
        <input formControlName="description" >
    </label>
    <label formGroupName="address">
        Address: 
        <input formControlName="description"  >
    </label>
    <label formGroupName="buildingType">
         Building type: 
        <input formControlName="description" >
    </label>    
</form>

现在问题是当我输出整个表单的值时,根据在formGroup(例如address或buildingType)中的嵌套字段控件中输入的内容,这些值并不真正更新。否则它会正常更新。

这是输出值的方式

<div>
   {{buildingForm.value | json}}
</div>

但是,如果createBuildingFG函数的执行方式不同,并且每个formControl都是显式创建的,只是传递整个对象,则表单正常运行。例如:

createBuildingFG(building: Building){
  let formGroup : FormGroup;
  formGroup = this.fb.group({
    doorsCount: '',
    description: '',
    address: this.fb.group({ description: ''}),
    buildingType: this.fb.group({ description: ''})
  });

  return formGroup;
}

任何人都可以解释发生了什么?显然,为了避免执行显式定义fromGroup的每个元素的繁琐任务,人们只想传递整个对象。

1 个答案:

答案 0 :(得分:3)

正如@jonrsharpe在评论中提到的那样

  

因为最初的建筑做了你不会随后做的事情   覆盖。

那是什么东西?

当angular创建FormGroup的新实例时,它调用_setUpControls方法

export class FormGroup extends AbstractControl {
  constructor(
      public controls: {[key: string]: AbstractControl},
      validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null,
      asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null) {
    super(
        coerceToValidator(validatorOrOpts),
        coerceToAsyncValidator(asyncValidator, validatorOrOpts));
    this._initObservables();
    this._setUpdateStrategy(validatorOrOpts);
    this._setUpControls();  <--------------

现在让我们来看看方法:

/** @internal */
_setUpControls(): void {
  this._forEachChild((control: AbstractControl) => {
     control.setParent(this);
     control._registerOnCollectionChange(this._onCollectionChange);
  });
}

我们可以看到每个控件项都设置了父项并注册了一些事件,但是你没有这样做。

以下代码应该有效:

formGroup = this.fb.group(building);
formGroup.controls.address = formGroup.controls.buildingType = null;
formGroup.registerControl('address', this.fb.group(building.address));
formGroup.registerControl('buildingType', this.fb.group(building.buildingType));

或者你可以使用递归来完成它的工作:

constructor(private fb: FormBuilder){
  this.buildingForm = this.createFormGroup(new Building);
}

createFormGroup(obj: any) {
  let formGroup: { [id: string]: AbstractControl; } = {};

  Object.keys(obj).forEach(key => {
    formGroup[key] = obj[key] instanceof Object ? this.createFormGroup(obj[key]) : new FormControl(obj[key]);
  });

  return this.fb.group(formGroup);
}