查找Reactive Form子组的错误

时间:2017-06-08 16:15:48

标签: angular angular2-forms

我找不到一种方法来检索我的被动形式的子组错误。

private setupFormValidation() {
    this.progressForm = new FormGroup({
      'preImplementationGroup': new FormGroup({
        'otherProgramName': new FormControl(null, [Validators.required]),
        'programType': new FormControl(null, [Validators.required]),
        ...
      }),
      'testingReviewGroup': new FormGroup({
        ...
      })
    });

仅为'preImplementationGroup'表单组找到所有错误的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

我找到了一种方法,万一有人会寻找类似的东西:

    sign() {
    var preImplementationGroup = <FormGroup>this.progressService.progressForm.get('preImplementationGroup');
    this.getFormValidationErrors(preImplementationGroup);
  }
  
  getFormValidationErrors(fg: FormGroup) {
    Object.keys(fg.controls).forEach(key => {

      const controlErrors: ValidationErrors = fg.get(key).errors;
      if (controlErrors != null) {
        Object.keys(controlErrors).forEach(keyError => {
          console.log('Key control: ' + key + ', keyError: ' + keyError + ', err value: ', controlErrors[keyError]);
        });
      }
    });
  }

答案 1 :(得分:0)

您可以使用FormBuilder构建表单组:

import {FormGroup, FormBuilder, Validators, FormControl} from "@angular/forms";
progressForm : FormGroup;
constructor(fb: FormBuilder) {}
private setupFormValidation() {
    this.progressForm = fb.group({
      'preImplementationGroup' :  fb.group({
        otherProgramName: [null, [Validators.required]],
        programType: [null, [Validators.required]]
      }),
      'testingReviewGroup' : fb.group({
        organisme: [null,[Validators.required]],
      })
});
}