如何在FormArray内的动态角度表单中添加新表单域

时间:2018-06-22 17:25:38

标签: angular typescript angular-reactive-forms angular-forms

我正在尝试创建一个动态的角度表单,我们可以在其中添加或删除一些新的表单字段到FormArray。

app.component.ts

import {Component, EventEmitter, OnInit} from '@angular/core';
import {CustomFormArray} from './custom-dynamic-form/components/custom-form-array/custom-form-array';
import {CustomRadio} from './custom-dynamic-form/components/custom-radio/custom-radio';
import {CustomCheckbox} from './custom-dynamic-form/components/custom-checkbox/custom-checkbox';
import {CustomInput} from './custom-dynamic-form/components/custom-input/custom-input';
import {CustomValidator, forbiddenNameValidator} from './custom-dynamic-form/services/custom-validator';
import {CustomFormGroup} from './custom-dynamic-form/components/custom-form-group/custom-form-group';
import {CustomSelect} from './custom-dynamic-form/components/custom-select/custom-select';
import {FormGroup, Validators} from '@angular/forms';
import {CustomButton} from './custom-dynamic-form/components/custom-button/custom-button';
import {EventService} from './event.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 myButton: CustomButton;
  filterArray: CustomFormArray;

  configs = [
    new CustomFormGroup({
      key: 'user_info',
      name: 'user_info',
      childrenField: [
        new CustomInput({
          key: 'first_name',
          label: 'First Name',
          type: 'text',
          value: 'John',
          placeholder: 'First Name',
          minLength: 4,
          maxLength: 10,
          validators: [Validators.required, Validators.minLength(4), Validators.maxLength(10)]
        }),
        new CustomInput({
          key: 'last_name',
          label: 'Last Name',
          type: 'text',
          value: 'Doe',
          placeholder: 'Last Name',
          validators: [Validators.required]
        }),
      ]
    }),

    new CustomRadio({
      key: 'gender',
      label: 'Gender',
      name: 'gender',
      value: 'male',
      radioOptions: [
        {label: 'Male', value: 'male', checked: true},
        {label: 'Female', value: 'female'}
      ]
    }),

    this.filterArray = new CustomFormArray({
      key: 'filterSettings',
      name: 'filterSettings',
      childrenField: []
    }),
  ];

  constructor(private eventService: EventService) {
  }

  ngOnInit() {

  }
}

stackblitz演示的链接: https://stackblitz.com/edit/angular-uiwrev

所以动态表单正在工作,但是当我尝试在click事件中动态在FormArray内添加新的formGroup时,却出现了此错误。

错误的屏幕截图: Error screenshot

0 个答案:

没有答案