angulartypescriptangular-reactive-forms

remove validators in angular reactive form not working


I have a condition that if it is true, I want to add a series of validations to some forms, and when the condition is not true, it will remove the validators.

Now, when I add the validator, it works properly, but when I try to remove it, it is not removed properly!!!

//html

<div [formGroup]="form">
    <p-checkbox (onChange)="changeShouldEnter()" name="shouldEnter" [value]="true"
          formControlName="shouldEnter"></p-checkbox>
    <label class="radio-lable mx-2">text</label>
</div>

//typescript

  ngOnInit(): void {    
    this.form = new FormGroup({
      shouldEnter: new FormControl([]),
      storeCategoryId: new FormControl(),
      storeCategoryItemCode: new FormControl(),
    })
  }


  changeShouldEnter() {
    if (this.form.get('shouldEnter').value[0]) {
      this.form.get("storeCategoryId").addValidators(Validators.required)
      this.form.get("storeCategoryItemCode").addValidators(Validators.required)
    } else {
      this.form.get("storeCategoryId").removeValidators(Validators.required)
      this.form.get("storeCategoryItemCode").removeValidators(Validators.required)
    }
    this.cdr.detectChanges();
  }

I even tried this way, but in the end, when I log the form, it is still invalid, and also inside the controls of that form, it says require: true again.

.removeValidators([Validators.required])
//or
.addValidators([])

Solution

  • When you add or remove validators make sure you call updateValueAndValidity, for the changes to be reflected.

    From the Docs:

    Recalculates the value and validation status of the control.

    By default, it also updates the value and validity of its ancestors.

      changeShouldEnter() {
        const shouldEnterCtrl = this.form.get('shouldEnter');
        const storeCategoryIdCtrl = this.form.get('storeCategoryId');
        const storeCategoryItemCodeCtrl = this.form.get('storeCategoryItemCode');
        if (shouldEnterCtrl?.value?.[0]) {
          storeCategoryIdCtrl.addValidators(Validators.required)
          storeCategoryItemCodeCtrl.addValidators(Validators.required)
        } else {
          storeCategoryIdCtrl.removeValidators(Validators.required)
          storeCategoryItemCodeCtrl.removeValidators(Validators.required)
        }
        storeCategoryIdCtrl.updateValueAndValidity(); // <- changed here!
        storeCategoryItemCodeCtrl.updateValueAndValidity(); // <- changed here!
      }