Search code examples
angularangular-formsangular-changedetection

Does calling updateValueAndValidity() on a FormControl trigger Angular's change detection


When calling updateValueAndValidity() on a Angular FormControl does this trigger Angular change detection for the component?

for example:

ngOnInit() {
    this.email.updateValueAndValidity();
    this.password.updateValueAndValidity();
}

Will this trigger change detection twice?

Is it more efficient to call ChangeDetectorRef.detectChanges() once?

Does this depend on what I set the emitEvent argument to?


Solution

  • For testing I used the following code to change two different FormControl values outside of Angular's change detection.

    this.zone.runOutsideAngular(() => {
      this.email.setValue('test@email');
      this.password.setValue('test-password');
    });
    

    Using the ngDoCheck Lifecycle hook, I was able to count how many times change detection was run.

    ngDoCheck() {
        console.log('checking for ', ++this.timesChecked);
    }
    

    Then I ran updateValueAndValidity() twice back within the zone and discovered that Angular change detection was only triggered once. Even when I set {onlySelf: true, emitEvent: false} it still only triggered it once.

    In conclusion it appears that if you need to trigger change detection for all FormControls its sufficient to either call updateValueAndValidity() on one form control or to call ChangeDetectorRef.detectChanges() once since both end up triggering a full change detection cycle.