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([])