i have form and i create that with reactive form in angular 9 .
in this form i have a toggle , when this toggle is true
the field moreAccountInfo
must have validation require and when not selected the toggle thet field must be the not requeire .
this is my form :
InitialFrom(): void {
this.addElectricMoneyFG = this.fromBuilder.group({
hasParent: [false],
parentId: [null],
name: ['', Validators.required],
code: ['', Validators.compose([Validators.required])],
type: ['', Validators.compose([Validators.required])],
hasAccountInfo: [false],
moreAccountInfo: [null],
description: ['', Validators.compose([Validators.required])],
published: [false]
})
}
and this is function for create a dynamic validation :
SetValidationMoreInfoValidation(): void {
this.addElectricMoneyFG.get('moreAccountInfo').setValidators(this.f.hasAccountInfo.value === true ? [Validators.required] : null);
this.addElectricMoneyFG.get('moreAccountInfo').updateValueAndValidity();
this.showMoreInfo = this.f.hasAccountInfo.value;
}
and when the uset click on the toggle this function is set :
<mat-slide-toggle
color="primary"
formControlName="hasAccountInfo"
(change)="SetValidationMoreInfoValidation()"
>
SetToggle /mat-slide-toggle
>
but its not worked .and the moreAccountInfo
is requierd . whats the problem ?