Angular 4 Reactive Forms Toggle Validation for Hidden Form Elements

I didn't find those solutions viable if you have a lot of optional fields in a complex form.

What I did is somtehing like that :

export class MyComponent implements AfterViewChecked {

 @ViewChildren(FormControlName) allFormControlInDOM: QueryList<FormControlName>;

 // ...

  ngAfterViewChecked(): void {
    // We must disable the controls that are not in the DOM
    // If we don't, they are used for validating the form
    if (this.allFormControlInDOM) {
      const controls: { [p: string]: AbstractControl } = this.myForm.controls;
      for (const control in controls) {
        if (controls.hasOwnProperty(control) && controls[control] instanceof FormControl) {
          const found = this.allFormControlInDOM.find((item: FormControlName) => item.name === control);
          if (found) {
            controls[control].enable();
          } else {
            controls[control].disable();
            controls[control].setValue(null);
          }
        }
      }
    }
  }

// ...

}

I hope that can help :)


In my application, I have a similar requirement. If the user asks to be notified by text, the phone is required. Otherwise the phone number is optional.

I wrote this method:

setNotification(notifyVia: string): void {
    const phoneControl = this.customerForm.get('phone');
    if (notifyVia === 'text') {
        phoneControl.setValidators(Validators.required);
    } else {
        phoneControl.clearValidators();
    }
    phoneControl.updateValueAndValidity();
}

It is called from this code which is in the ngOnInit:

    this.customerForm.get('notification').valueChanges
                     .subscribe(value => this.setNotification(value));

If the user changes the notification field (which is a radio button), it calls the setNotification method passing in the value. If the value is notification by 'text', it sets the phone's validation to required.

Otherwise it clears the phone field's validation.

Then it must call updateValueAndValidity to update the form info with this new validation.


I think the best option for to do this it's make fields part of inital form with all theirs validations and when you want disable and enable fields or nested forms programmatically.

Example: https://stackblitz.com/edit/angular-ojebff

https://stackblitz.com/edit/angular-ojebff?embed=1&file=app/input-errors-example.html


Even the fields are hidden from user the fields are active in the reactive from. So simply you need to disable the field from the reactive from by using following code

this.myForm.get("nickName").disable();

Change the function toggleNick() as given below

toggleNick() {
    this.showNick = !this.showNick;
    if(showNick) {
         this.myForm.get("nickName").enable();
    } else {
         this.myForm.get("nickName").disable();
    }
}