以动态形式实现FormArray-角度

时间:2018-10-18 04:01:23

标签: javascript angular typescript angular-reactive-forms

我基于this article的动态形式。我需要创建一个FormArray字段,但在实现过程中不断出错。下面的代码分别显示了用于阵列的开关盒的打字稿代码和代码片段。我收到错误Error: Cannot find control with path: 'anArray -> anArray'。动态表格的FormArray设置有什么问题?

form: FormGroup;

ngOnInit() {
  // remap the API to be suitable for iterating over it
  this.objectProps =
    Object.keys(this.dataObject)
    .map(prop => {
      return Object.assign({}, {
        key: prop
      }, this.dataObject[prop]);
    });
  var str = JSON.stringify(this.objectProps, null, 2);

  // setup the form
  const formGroup = {};
  for (let prop of Object.keys(this.dataObject)) {
    if (prop == "anArray") {
      formGroup[prop] = this.fb.array([
        [''],
      ])
    } else {
      formGroup[prop] = new FormControl(this.dataObject[prop].value || '', this.mapValidators(this.dataObject[prop].validation));
    }
  }

  this.form = new FormGroup(formGroup);
}

addFormInput(field) {
  const form = new FormControl('');
  ( < FormArray > this.form.controls[field]).push(form);
}

removeFormInput(field, i) {
  ( < FormArray > this.form.get(field)).removeAt(i);
}
<div *ngSwitchCase="'array'">
  <label>{{prop.key}}</label>
  <div formArrayName="{{prop.key}}" [id]="prop.key">
    <br>
    <div formArrayName="{{prop.key}}" *ngFor="let item of form.get(prop.key).controls; let i = index;">
      <div [formGroupName]="i">
        <input [formControlName]="prop.key" [placeholder]="prop.label">
      </div>
      <div>
        <button type="button" class="btn" (click)="removeFormInput(prop.key, i)">x</button>
      </div>
    </div>
  </div>
  <div>
    <button id="btn-add" type="button" class="btn" (click)="addFormInput(prop.key)">Add</button>
  </div>
</div>

下面的示例数据输入

export const person = {
  name: {
    label: 'Name',
    value: 'Juri',
    type: 'text',
    validation: {
      required: true
    }
  },
 anArray: {
    label: 'Name',
    value: 'Juri',
    type: 'array',
    validation: {
      required: true
    }
  },
  age: {
    label: 'Age',
    value: 32,
    type: 'text'
  },
  gender: {
    label: 'Gender',
    value: 'M',
    type: 'radio',
    options: [
      { label: "Male", value: 'M'},
      { label: "Female", value: 'F'}
    ]
  }, 
  city: {
    label: 'City',
    value: '39010',
    type: 'select',
    options: [
      { label: "(choose one)", value: ''},
      { label: "Bolzano", value: '39100'},
      { label: "Meltina", value: '39010'},
      { label: "Appiano", value: '39057'}
    ],
    validation: {
      required: true
    }
  }
}

0 个答案:

没有答案