Handle Angular ReactiveForm validatorsOct 20, 2017 - 1 minutes read
Table of content
Sometimes we need to enable or disable the validators which are already have been initialize. Something like below
The problem here is after
this.form.value.type has changed and the value is not equal 1 so the form validators will be change. We’ll be remove validation for
house field and make the vadidation for
How can do that? Fortunately, Angular is provided to us two functions to do that in the run-time : - setValidators and setAsyncValidators - updateValueAndValidity
setValidators: Sets the synchronous validators that are active on this control. Calling this will overwrite any existing sync validators.
setValidators but it will work with async
updateValueAndValidity: Re-calculates the value and validation status of the control.
Follow by above definition, we can make the manual validators like as:
Sometimes for better performance, we should make the debounce time when the value change.