leo-boy
leo-boy

Reputation: 77

Dynamic form validation in angular 6 with condition and vice versa

I am working on angular 6 with dynamic form validation. I have three form fields gender which is initially with required validation; ageFrom and ageTo which are to be validated dynamically. If ageFromvalue is first entered then the validation for ageTo is to be made required where as when ageTo value is first entered then the validation for ageFrom is to be made required. My code is as below:

this.formGroup = this.fb.group({
          ageTo: [''],
          ageFrom: [''],
          gender: new FormControl('', Validators.required),

      });

      const ageFrom = <FormControl>this.formGroup.get('ageFrom');
      const ageTo = <FormControl>this.formGroup.get('ageTo');

      this.subscription = ageFrom.valueChanges.subscribe(value => {
          if (value) {
              ageTo.setValidators([Validators.required,]);
          } else {
              ageTo.setValidators([Validators.nullValidator,]);
          }
          this.formGroup.updateValueAndValidity();
      });

      this.subscription = ageTo.valueChanges.subscribe(value => {
          if (value) {
              ageFrom.setValidators([Validators.required,]);
          } else {
              ageFrom.setValidators([Validators.nullValidator,]);
          }
          this.formGroup.updateValueAndValidity();
      });

After this code as it goes on infinite loops. It gives ERROR RangeError: Maximum call stack size exceeded How can I solve that conditional and vice versa dynamic form validation.

Upvotes: 0

Views: 547

Answers (1)

Chellappan வ
Chellappan வ

Reputation: 27293

set emitEvent false to updateValueandValidity method.

 ngAfterViewInit() {
        const ageFrom = <FormControl>this.formGroup.get("ageFrom");
        const ageTo = <FormControl>this.formGroup.get("ageTo");

        ageFrom.valueChanges.subscribe(value => {
          console.log(value, "ageFrom");
          if (value) {
            ageTo.setValidators(Validators.required);
          } else {
            ageTo.setValidators(Validators.nullValidator);
          }
          ageTo.updateValueAndValidity({ emitEvent: false });
        });

        ageTo.valueChanges.subscribe(value => {
          console.log(value, "ageTo");
          if (value) {
            ageFrom.setValidators(Validators.required);
          } else {
            ageFrom.setValidators(Validators.nullValidator);
          }
          ageFrom.updateValueAndValidity({ emitEvent: false });
        });
      }

Example

Upvotes: 2

Related Questions