问题描述
我有一个FormGroup
定义,如下所示:
I have a FormGroup
defined like below:
this.businessFormGroup: this.fb.group({
'businessType': ['', Validators.required],
'description': ['', Validators.compose([Validators.required, Validators.maxLength(200)])],
'income': ['']
})
现在,当businessType
是Other
时,我想从description
中删除Validators.required
验证器.如果businessType
不是Other
,我想添加回Validators.required
.
Now when businessType
is Other
, I want to remove Validators.required
validator from description
. And if businessType
is not Other
, I want to add back the Validators.required
.
我正在使用以下代码动态添加/删除Validators.required
.但是,它会清除现有的Validators.maxLength
验证器.
I am using the below code to dynamically add/remove the Validators.required
. However, it clears the existing Validators.maxLength
validator.
if(this.businessFormGroup.get('businessType').value !== 'Other'){
this.businessFormGroup.get('description').validator = <any>Validators.compose([Validators.required]);
} else {
this.businessFormGroup.get('description').clearValidators();
}
this.businessFormGroup.get('description').updateValueAndValidity();
我的问题是,添加/删除required
验证器时如何保留现有验证器.
My question is, how can I retain the existing validators when adding/removing the required
validator.
推荐答案
角度表单具有内置函数 setValidators(),可通过程序分配验证程序.
Angular forms have a built in function setValidators() that enables programmatic assignment of Validators.
对于您的示例,您可以执行以下操作:
For your example you can do:
if(this.businessFormGroup.get('businessType').value !== 'Other'){
this.businessFormGroup.controls['description'].setValidators([Validators.required, Validators.maxLength(200)]);
} else {
this.businessFormGroup.controls['description'].setValidators([Validators.maxLength(200)]);
}
请务必记住,使用此方法将覆盖现有的验证器,因此您将需要包括/需要用于重置控件的所有验证器.
It is important to keep in mind that by using this method you will overwrite your existing validators so you will need to include all the validators you need/want for the control that you are resetting.
这篇关于Angular-动态添加/删除验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!