Angular Reactive Forms - Enabled/Disabled Form Control not correctly reflected on UI after...

Discussão em 'Angular' iniciado por JamesBV3, Fevereiro 6, 2025.

  1. JamesBV3

    JamesBV3 Guest

    I have a test angular reactive form, where you can enable/disable a Form Control, and apply required/optional validation.

    I am running into an issue where the FormControl enabled/disabled state is not correctly reflected in the UI when re-initializing the reactive form.

    Example Setup:

    first_name: AbstractControl;

    constructor(private fb: FormBuilder, private cdr: ChangeDetectorRef) {
    this.buildForm();
    }

    buildForm(): void {
    this.form = this.fb.group({
    first_name: new FormControl({ value: null, disabled: false }, [
    Validators.maxLength(10),
    ]),
    });

    this.first_name = this.form.controls.first_name;
    }


    By default, the control is enabled, so I have a method to disable the control

    disable(): void {
    this.first_name.disable();
    }


    I want to be able to reset this form group back to the original state, so I call "buildForm()" and "updateValueAndValidity()" to re-initialize the form.

    rebuild() {
    this.buildForm();
    this.form.updateValueAndValidity();
    }

    • This resets the value, validators, and enabled/disabled state of each form control.
    • Everything appears to be correctly reset in the form, however, the enabled/disabled state is NOT correctly reflected on the UI
    • As a result, the input is still disabled in the UI, even though the control is correctly reset back to enabled.

    I have found a workaround, shown below, although having to call:

    • Call form.reset(), and set the disabled state back to the original value BEFORE re-initializing the form. This seems like it should not be required.

    reset() {
    this.form.reset({
    first_name: { value: '', disabled: false },
    });
    }

    rebuild() {
    this.reset();
    this.buildForm();
    this.form.updateValueAndValidity();
    }


    I would use form.reset() alone, however, it does not allow the original validators to be re-applied, so I would have to call control.setValidators for each control. I would like to have a single piece of logic for initializing and re-initializing the form.

    Stackblitz link

    To reproduce:

    • The Input field is enabled by default
    • Click "Disable", and the input is now disabled
    • Click "Rebuild Form". The input remains disabled, even though the form control itself is not disabled

    So, my question is,

    • Is there a way to ensure the input field correctly reflects a controls enabled/disabled state when the form is re-initialized without needing to call form.reset()?

    Continue reading...

Compartilhe esta Página