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

huangapple go评论64阅读模式
英文:

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

问题

The ngDoCheck() hook is called when you focus out from an <input> tag because it is triggered whenever Angular's change detection mechanism runs, which can happen for various reasons, including input field events. In your case, when you type or focus out from the <input> field, Angular checks for changes in the associated [(ngModel)]="text" binding, which triggers the ngDoCheck() hook. This is part of Angular's lifecycle and change detection process.

英文:

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

Here I've add one &lt;input&gt; tag in app.component.html with [(ngModel)]=&quot;text&quot; 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 <input> field. Please help me to get this.

Here is my app.component.html code

&lt;input type=&quot;text&quot; name=&quot;name&quot; id=&quot;&quot; [(ngModel)]=&quot;text&quot; /&gt;

Here is my app.component.ts code

import { Component, DoCheck } from &#39;@angular/core&#39;;

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

  constructor() {}

  ngDoCheck(): void {
    console.log(&#39;AppComponent ngDoCheck&#39;);
  }
}

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

答案1

得分: 2

ngDoCheck 在每次发生变更检测时调用 - 并且变更检测会在每次可能改变应用程序状态的用户交互之后发生。

失去焦点的字段会改变 NgModel 组件的状态。更具体地说,它会导致该组件获得touched状态,并且输入框会接收 ng-touched CSS 类。

英文:

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.

huangapple
  • 本文由 发表于 2023年5月15日 00:13:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76248491.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定