Angular
Intro to Reactive Forms in Angular - Validate Forms

Update Validators Dynamically

Mute
Current Time 0:00
/
Duration Time 0:00
Loaded: 0%
Progress: 0%
Stream TypeLIVE
Remaining Time -0:00
 
PRO

In this video, I'll show you how to dynamically update a Validator. Let's say we have a scenario where we want a text input to show up if the user selects a location of "Other". If that input shows up, it's required to be filled in. When the form loads, this form control has no Validators. We want to add the Validator.required on the fly if the user has selected "Other". In order to do this, we'll subscribe to the value changes of the location form control, which represents the location radio button group. After form initialization, we'll add:
this.location.valueChanges.subscribe(loc => { if(loc === "other") { this.otherLocation.setValidators(Validators.required) } else { this.otherLocation.setValidators(null); } this.otherLocation.updateValueAndValidity(); });

Learn more about the method updateValueAndValidity() in the documentation.

 

I finished! On to the next chapter