Angular form updateValueAndValidity of all children controls

后端 未结 5 647
攒了一身酷
攒了一身酷 2020-12-29 01:50

In my Angular 4 app, I have a form with several controls.

At some points I need to force the update of their validity, so I\'m doing:

this.form.get(\         


        
5条回答
  •  [愿得一人]
    2020-12-29 02:37

    I ran into the same problem, one of the issues was that listening to the valueChanges observable and triggering updateValueAndValidity to run my validators caused an endless loop, so to resolve (and somewhat hacky ?) I created the component variable validityCycleFired and initialized as false, that I toggle and it prevents a runaway loop:

    const fireValidityCheck = () => {
         if (this.validityCycleFired) return;
         this.validityCycleFired = true;
         this.passwordForm.get('old_password').updateValueAndValidity();
         this.passwordForm.get('new_password').updateValueAndValidity();
         this.passwordForm.get('confirm_new_password').updateValueAndValidity();
         setTimeout(() => this.validityCycleFired = false, 15);
         return;
    };
    this.passwordForm.valueChanges.subscribe(fireValidityCheck);
    

提交回复
热议问题