user9343182
user9343182

Reputation:

Angular programmatically required validator not working

I have got a checkbox which displays some fields and hides some depending on its value (checked or not)

When it changes, I call a method to set validators of the previous fields to not required and I set new displayed validators to required.

onSwitchCheckbox({ checked: isChecked }) {
    // small timeout to give time to DOM to render the fields because they are hidden with *ngIf="isCheckedCheckBox" (isCheckedCheckBox is a global variable)
    setTimeout(() => {
        this.isCheckedCheckBox = isChecked;
        if (isChecked) {      
            this.formGroup.controls.fieldB.setValidators([Validators.required]);
            this.formGroup.controls.fieldC.setValidators([Validators.required]);
            this.formGroup.controls.fieldA.clearValidators();
        } else {
            this.formGroup.controls.fieldB.clearValidators();
            this.formGroup.controls.fieldC.clearValidators();
            this.formGroup.controls.fieldA.setValidators([Validators.required]);
        }
    
        // update fields
        this.formGroup.updateValueAndValidity();
    }, 200);
}

The problem is that the fieldA stays required and the fields B and C never get required no matter if the checkbox is checked or not

What's wrong with my code ?

Thank you very much

Upvotes: 1

Views: 986

Answers (1)

Adrita Sharma
Adrita Sharma

Reputation: 22203

You need to updateValueAndValidity of the fieldA formControl

Try like this:

this.formGroup.controls.fieldA.clearValidators();
this.formGroup.controls.fieldA.updateValueAndValidity();

Working Demo

Upvotes: 1

Related Questions