0

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 ?

kianoush dortaj
  • 411
  • 7
  • 24
  • if you disabled the control, Angular not validate the control, so I suggest you disable the control. For do it use a directive: https://stackoverflow.com/questions/47937639/how-to-make-a-disabled-reactive-form-editable-in-angular2/47938138#47938138 – Eliseo Jun 08 '20 at 07:44

1 Answers1

0

angular 5 conditionally validate field based on another field's value

const control1 = <FormControl>this.form.get('control1');
const control2 = <FormControl>this.form.get('control2');

control1.valueChanges.subscribe(value => {
  if (value === 'first-condition') {
    control2.setValidators([Validators.required, ...])
  }
  else {
    control2.setValidators(null);
  }

  control2.updateValueAndValidity();
});
Ahmed ElMetwally
  • 2,276
  • 3
  • 10
  • 15