DINH DUONG

Handle Angular ReactiveForm validators

Oct 20, 2017 - 1 minutes read

Table of content

Reason

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 apartment field.

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.

setAsyncValidators: Same setValidators but it will work with async validator

updateValueAndValidity: Re-calculates the value and validation status of the control.

Implementation

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.

this.form.controls['type'].valueChanges.debounceTime(100).subscribe()

Back to posts

angular english
github twitter codfee email