I have a FormGroup
defined like below:
this.businessFormGroup: this.fb.group({
'businessType': ['', Validators.required],
'description': ['', Validators.compose([Validators.required, Validators.maxLength(200)])],
'income': ['']
})
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
.
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();
My question is, how can I retain the existing validators when adding/removing the required
validator.
question from:
https://stackoverflow.com/questions/49075027/angular-dynamically-add-remove-validators 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…