使用FormArray

时间:2018-12-17 13:41:21

标签: angular5 angular6 angular2-forms angular-reactive-forms validationsummary

在我的表单中,很少使用FormArray来动态生成输入字段文本框,它对每个字段都具有相同的formControlName,但具有唯一的ID。这样我们就可以生成动态输入字段

monthList: any[];
// process to create day forms controls.
  initMonthControls(): void {
    // prepare array for which controls need to be created.
    const monthLabels = [
      { rateTypeId: Types.WholeMonth, text: 'Whole month', rate: '' },
      { rateTypeId: Types.HalfMonth, text: 'Half month', rate: '' },
    ];
    this.monthList = monthLabels;
    // create input controls for each item.
  const manageFormArray = <FormArray>this.manageForm.controls['month'];
    manageFormArray.controls.length = 0;
    for (let i = 0, length = items.length; i < length; i++) {
      manageFormArray.push(this.formBuilder.group({
        rateTypeId: [(items[i].rateTypeId)],
        rate: [items[i].rate, Validators.pattern(ValidationPatterns.money)],
      }));
    }
  }

,我需要根据有效输入在页面顶部创建一个验证摘要。 当我有唯一的formcontrolname时,我可以通过这种方式正确显示验证摘要:

在manage.constants.ts中,我有:

 manageDetails: [
        {
            id: 'rate1',
            name: 'January',
            label: 'January Month',
        },
        {
            id: 'rate2',
            name: 'February',
            label: 'February Month',
        },
], 

     // find the errors from each controls from form group.
          generateErrorMessages(formGroup: FormGroup): void {
            Object.keys(formGroup.controls).forEach((controlName) => {
              const control = formGroup.controls[controlName];
              if (control instanceof FormGroup) {
                // recursive function to find form group.
                this.generateErrorMessages(control);
              }
              this.errorMessages(control, controlName);
            });
          }
and to push error messages we have
    errorMessages() {
    // get the control details
        const item = this.formControlList.filter((x) => x.name === controlName)[0];
        if (errors.required) {
          this.errors.push(this.generateErrors(item.id, item.label + ' ' + ’is required’);
        }
    }

由于我基于formcontrolname进行过滤,因此当我在动态生成的字段中没有唯一的formcontrolname时,我将面临问题。 能否请您提出一些解决方案,以便在我没有唯一的formControlName时显示验证摘要

0 个答案:

没有答案