Angular 反应式表单设置和清除验证器 [英] Angular reactive forms set and clear validators
问题描述
请协助,我想删除表单中的所有验证器,请告知是否可行,如果不可行,如果您有一个包含 20 个或更多表单控件的表单组,则删除验证器的更好方法是什么,请参见下面的示例.
Please assist, i want to remove all validators in form, Please advise if its possible or not and if not whats the better way to remove validators if you have a form Group of 20 or more form controls, see example below.
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 个或更多控件清除和设置验证器的情况下可能会很痛苦,因此非常感谢有关如何处理此类情况的地图.
The above method addValidators()
will add validators and removeValidators()
will remove validators when executed. but the problem i have is, i have to specify the form control im trying to clear validators. is there a way to just do this.exampleFormGroup.clearValidators();
and clear all in the form and again this.exampleFormGroup.setValidators()
to set them back. i know i may be asking for a unicorn but in a scenario where the formGroup has 20 or more controls clearing and setting validators can be painful so a map on how to handle such scenarios will be much appreciated.
推荐答案
你可以这样做:
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();
}
}
这篇关于Angular 反应式表单设置和清除验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!