英文:
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 <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 <input> 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
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论