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(); } |
上面的方法
您可以执行以下操作:
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(); } } |