Angular Hooks (Angular Lifecycle Hooks)

wordpress featured image

Angular hooks (written in short for Angular Lifecycle Hooks) is the lifecycle that a component goes through in it’s process from instantiation, through changes, to it’s end of destruction state.

The lifecycle starts with Angular initializing a component, and rendering it in the view, along with it’s child components. It then initializes the change detection cycle, in which it looks for changes to properties of the component class, and update the view and component as and when needed. The lifecycle ends when Angular destroys the component and removes it from the view and DOM.

During this whole lifecycle, Angular gives access to different events happening within the component. This access points to events, is what is known as Lifecycle Hooks, or Angular Hooks in general. We can use these exposed hooks, as an opportunity to run any additional piece of code, if required.

For example: If we want to log when a component got initialized, we can use one of the hooks from the framework, that is OnInit hook

// Implementing the OnInit hook which exposes ngOnInit() function for implementation
export class MyComponent implements OnInit {
  ngOnInit() {
    console.log('MyComponent initialized');
  }
}

Available Lifecycle Events/Hooks

1. ngOnChanges()

This is called for the 1st time before ngOnInit() if there are Input() changes. This is then called multiple times whenever any bound property changes it’s value.
The ngOnChanges() function will have an argument of type SimpleChanges which will have details on what changed during the cycle.

2. ngOnInit()

This is only called once during the initialization of the component along with its properties.

3. ngDoCheck()

This is called once after ngOnInit() hook and then after every-time ngOnChanges() hook is triggered

4. ngAfterContentInit()

This is called once after ngDoCheck()
This is triggered when the Component’s view is rendered to the screen.

5. ngAfterContentChecked()

This is called after ngAfterContentInit() and every ngDoCheck()
This responds to changes done on the content that is projected on the screen.

6. ngAfterViewInit()

Called once after the first ngAfterContentChecked()
This is triggered when the component and it’s child views have been rendered on screen.

7. ngAfterViewChecked()

Called once after ngAfterViewInit() and then on every subsequent ngAfterContentChecked()
This is triggered after Angular has checked the component’s and it’s child’s views.

8. ngOnDestroy()

This is called just before Angular destroys the Component
This hook can be used to do cleanup (like unsubscribing Observables and detaching event handlers) for avoiding memory leaks.

Official documentation on Angular Lifecycle Hooks can be found here, and more details on Angular from me can be found here.

Leave a Reply