Wednesday, 24 January 2024

ngDoCheck life cycle hook.

The ngDoCheck lifecycle hook in Angular is part of the change detection mechanism. It is called by Angular during every change detection cycle, which is the process by which Angular updates the view based on changes in the component. 

The purpose of ngDoCheck is to detect and act upon changes that Angular doesn't catch automatically. Unlike other lifecycle hooks, ngDoCheck doesn't have a corresponding interface; instead, it's a method that you implement in your component class.


Here's how you can use ngDoCheck in a component:





































In this example:

  • We have a UserComponent with an @Input() property called user, which is an object containing the user's name and email.
  • We use the ngDoCheck method to check if the user's name has changed compared to the previous state. If it has changed, we log a message to the console.
  • We maintain a previousName property to store the last known name. This is important to compare with the current name in each ngDoCheck call.

Now, when you use this component in a parent component's template, such as:























And in the parent component's TypeScript file:









































Clicking the "Change User's Name" button will trigger a change in the user's name, and you will see corresponding messages logged to the console by the ngDoCheck method in the UserComponent.


No comments:

Post a Comment