Component Lifecycle Hooks

To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video

PRO

Weyou!

Help spread the word about this tutorial!

In Angular 1, we had access to an attribute directive (ng-init) where we could run a method from our $scope on the page initialization procedure. This Lifecycle Hook has now been expanded in Angular 2 to support a variety of events that we can target. Currently, there are now eight supported lifecycle hooks. The most commonly used hooks are:

ngOnChanges

This is called when data changes in your application that affects this component specifically

ngOnInit

This is called when the component initializes for the first time (i.e. it's only called once)

ngOnDestroy

This is called when the component is about to be destroyed (i.e. removed from the page)

Each of these hooks can be useful for running methods during specific events triggered by a component during its instantiation, modification, and existence. Attaching a lifecycle hook is quite simple and only requires three steps: