Search code examples
javascriptangulartypescriptangular-reactive-forms

How to do required-if in Angular Reactive Forms?


I have a reactive form and based on the property fooRequired I want to set the field to be required or not.

I can't change that because it set at initial. so what can I do?

fooRequired = false;

form = new FormGroup({
 foo: new FormControl(null, [Validators.required])
});

toggle() { this.fooRequired = !this.fooRequired; }

Solution

  • The following will do the trick:

    toggle() {
      this.fooRequired = !this.fooRequired;
      this.form.controls.foo.setValidators(this.fooRequired ? null : [Validators.required]);
      this.form.controls.foo.updateValueAndValidity();
    }
    

    Here, based on the fooRequired boolean, the validators are set or removed. Finally, the new form control settings are updated.