angularangular-componentsangular-lifecycle-hooksangular-component-life-cycle

Unnecessary call of ngDoCheck() hook in Angular, why this happens?


Why does ngDoCheck() hook gets called when I focused out from an tag?

Here I've add one <input> tag in app.component.html with [(ngModel)]="text" associates to it. I can understand ngDoCheck() hook get's called whenever I type(update) in input field because it updates the text field in app component. But why it is being called when I moved/focusOut from the field. Please help me to get this.

Here is my app.component.html code

<input type="text" name="name" id="" [(ngModel)]="text" />

Here is my app.component.ts code

import { Component, DoCheck } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements DoCheck {
  text: any = 'Hi';

  constructor() {}

  ngDoCheck(): void {
    console.log('AppComponent ngDoCheck');
  }
}

In the below video debugger stops on ngDoCheck() when I click outside input field. ngDoCheck debugger gif


Solution

  • ngDoCheck is called whenever change detection occurs - and change detection occurs after every user interaction that might have changed the state of the app.

    The field losing focus changes the state of the NgModel component. More specifically, it causes the component to get the touched state, and the input to receive the ng-touched CSS class.