Search code examples
angularvalidationdisable

Angular: disable a formfield and keep form invalid


I have a main form which embed a formArray

  initForm() {
    this.mainForm = this.formBuilder.group({
      label: ['', [Validators.required, Validators.maxLength(this.labelMaxLength)]],
      foos: this.formBuilder.array([]),
    });
  }

foo is a subform (another component) :

  initForm() {
    this.subForm = this.formBuilder.group({
      name: ['', [Validators.required, Validators.maxLength(this.labelMaxLength)]],
      bar: new FormControl('',[Validators.required]),
    });
  }

in my process I need to disable the bar field temporally, which I perform with : this.subForm.get('bar').disable();

As expected, the field is disabled, and the associated validators are not taken into account anymore.

In my case, I need to keep the bar validator, or at least set the subForm invalid when bar is disabled.

I tried to do in the subcomponent this.subForm.setErrors({incorrect: true}); but the main form consider the foos formArray valid and allow form submission...

thank you for your help,


Solution

  • In the way to show error on bar is disabled you should make Validator for the FormGroup, like that:

    this.subForm = this.formBuilder.group({
          name: ['', [Validators.required, ...]],
          bar: new FormControl('',[Validators.required]),
        }, { validator: [barValidation] });
    

    and make your custom validator:

    export const barValidation: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
      const bar = control.get('bar');
      return bar.disabled ? { 'bar is disabled': true } : null;
    };
    

    Now FormGroup invalid when bar is disabled.