Angular 1.5.3 lifecycle-hooks
The first lifecycle-hooks on Angular 1 landed in version 1.5, but more were introduced in version 1.5.3.
What’s it all about?
Lifecycle hooks landed first in the Angular 2 alpha release.
With 1.5.3 components have become a bit smarter and a bit more compatible with Angular 2. This new version introduced some new and useful lifecycle hooks to directive/component controllers.
Recap: $onInit
Angular 2 (equivalent) : $onInit()
I’ve previously written about $onInit, the first lifecycle hook introduced with version 1.5. Have a look at my post here.
It provides you with a nice, clean place to initialize your component after all of its bindings have been set. It’s the best place for http requests during initialization of the component or controller for example.
New: $onChanges
Angular 2 (equivalent) : $onChanges(changesObj)
This hook allows us to react to changes of one-way bindings of a component and is similar to ng2’s ngOnChanges.
If you are used to using $watch to do work whenever a value you’re bound to changes, using this hook make things clearer and removes the need to introduce a watch and a dependency on $scope.
Example using $onInit & $onChanges:
New: $onDestroy
Angular 2 (equivalent) : $onDestroy()
This hook is called when the controller’s scope is being destroyed. It’s a useful hook when we want to release watches, external resources and event handlers.
Before the version 1.5.3 of Angular, we would use this hook as:
$scope.$on(’$destroy’, ...)
But using the version 1.5.3 we can get rid of the $scope dependency and use this hook as:
this.$onDestroy = function () {
//do something
};New: $postLink
Angular 2 (equivalent) : $postLink()
Called after the controller’s element and its children have been linked. This hook can be used to set up DOM event handlers and to do direct DOM manipulation. This hook can be considered analogous to the ngAfterViewInit and ngAfterContentInit hooks in Angular 2.
It’s getting really interesting how Angular team are moving things forward from Angular 1 to Angular 2.
Really exciting to see the progress and the next releases of Angular 1.x!