角反应形式设置并清除验证器

Angular reactive forms set and clear validators

请协助,我想删除表格中的所有验证器,请告知是否可能,如果您有20个或更多表格组的表格控件,那么删除验证器的更好方法是什么,请参见下面的示例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 ngOnInit() {
    this.exampleFormGroup = this.formBuilder.group({
     surname: ['', [Validators.required, Validators.pattern('^[\\\\w\\\\s/-/(/)]{3,50}$')]],
     initials: ['', [Validators.required, Validators.maxLength(4)]]
     });
  }

 public removeValidators() {
    this.exampleFormGroup.get('surname').clearValidators();
    this.exampleFormGroup.get('initials').clearValidators();
    this.exampleFormGroup.updateValueAndValidity();
 }

 public addValidators() {
  this.exampleFormGroup .get('surname').setValidators([Validators.required,Validators.pattern('^[\\\\w\\\\s/-/(/)]{3,50}$')]);
  this.exampleFormGroup.get('initials').setValidators([Validators.required, Validators.maxLength(4)]);
  this.exampleFormGroup.updateValueAndValidity();
 }

上面的方法addValidators()将添加验证器,而removeValidators()将在执行时删除验证器。 但是我的问题是,我必须指定试图清除验证器的表单控件。 有没有办法做this.exampleFormGroup.clearValidators();并清除表格中的所有内容,然后再次this.exampleFormGroup.setValidators()将它们重新设置。 我知道我可能会要求独角兽,但在formGroup具有20个或更多控件的情况下,清除和设置验证器可能会很痛苦,因此,将非常感谢有关如何处理此类情况的地图。


您可以执行以下操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
validationType = {
    'surname': [Validators.required, Validators.pattern('^[\\\\w\\\\s/-/(/)]{3,50}$')],
    'initials': [Validators.required, Validators.maxLength(4)]
}

ngOnInit() {
    this.exampleFormGroup = this.formBuilder.group({
        surname: ['', [Validators.required, Validators.pattern('^[\\\\w\\\\s/-/(/)]{3,50}$')]],
        initials: ['', [Validators.required, Validators.maxLength(4)]]
    });
}

    public removeValidators(form: FormGroup) {
    for (const key in form.controls) {
        form.get(key).clearValidators();
        form.get(key).updateValueAndValidity();
    }
}
     

    public addValidators(form: FormGroup) {
    for (const key in form.controls) {
        form.get(key).setValidators(this.validationType[key]);
        form.get(key).updateValueAndValidity();
    }
}