Lifecycle hooks

Hooks for the Component

Constructor

This is invoked when Angular creates a component or directive by calling new on the class.

ngOnChanges

Invoked every time there is a change in one of the input properties of the component.

ngOnInit

Invoked when the given component has been initialized. This hook is only called once after the first ngOnChanges

ngDoCheck

Invoked when the change detector of the given component is invoked. It allows us to implement our own change detection algorithm for the given component.

ngDoCheck and ngOnChanges should not be implemented together on the same component.

ngOnDestroy

This method will be invoked just before Angular destroys the component. Use this hook to unsubscribe observables and detach event handlers to avoid memory leaks.

Hook method

Purpose

Timing

ngOnChanges()

Respond when Angular sets or resets data-bound input properties.

Called before ngOnInit() and whenever one or more data-bound input properties change.

Note that if your component has no inputs or you use it without providing any inputs, the framework will not call ngOnChanges().

ngOnInit()

Initialize the directive or component after Angular first displays the data-bound properties and sets the directive or component's input properties.

Called once, after the first ngOnChanges().

ngDoCheck()

Detect and act upon changes that Angular can't or won't detect on its own.

Called immediately after ngOnChanges() on every change detection run, and immediately after ngOnInit() on the first run.

ngAfterContentInit()

Respond after Angular projects external content into the component's view, or into the view that a directive is in.

Called once after the first ngDoCheck().

ngAfterContentChecked()

Respond after Angular checks the content projected into the directive or component.

Called after ngAfterContentInit() and every subsequent ngDoCheck().

ngAfterViewInit()

Respond after Angular initializes the component's views and child views, or the view that contains the directive.

Called once after the first ngAfterContentChecked().

ngAfterViewChecked()

Respond after Angular checks the component's views and child views, or the view that contains the directive.

Called after the ngAfterViewInit() and every subsequent ngAfterContentChecked().

ngOnDestroy()

Cleanup just before Angular destroys the directive or component. Unsubscribe Observables and detach event handlers to avoid memory leaks.

Called immediately before Angular destroys the directive or component.

Last updated