Exploring Angular 1.5: Lifecycle Hooks

Angular 1.5 has been finally released and it’s more powerful than ever before! Many new features have been added and tons of fixes landed in the latest bigger release. If you’re following our articles, you know that we love to give an overview of the latest and greatest in the Angular world. Last year we blogged about the 1.3 release in our article series Exploring Angular 1.3. With this article we’re going to start a new series called, guess what, “Exploring Angular 1.5”, and the first topic we’re going to explore is the new feature of Lifecycle Hooks. Let’s get started right away!

Lifecycle Hooks

Lifecycle hooks in Angular landed first in the Angular 2 alpha release and they are more or less inspired by the Custom Elements lifecycle callbacks. By inspired we mean that they are not exactly the same. They’re not only named differently and do different things, there are also more. An Angular 2 component comes with lifecycle hooks like ngOnInit(), ngOnDestroy(), ngOnChanges() and many more. We get a very detailed overview of these in the official docs.

However, this article is on Angular 1.5. Since Angular 1 is evolving in a way to keep the gap to Angular 2 as small as possible, some lifecycle callbacks have been backported to the current “best Angular yet”. Let’s take a look at them one by one.

Note: The Angular lifecycle-hooks were introduced in version 1.5.3.

$onInit()

This lifecycle hook will be executed when all controllers on an element have been constructed and after their bindings are initialized. This hook is meant to be used for any kind of initialization work of a controller. To get a better idea of how this behaves, let’s take a look at some code.

We start off with an Angular 1.5 componentmyCmp. A component has a controller and a template, and in our example, our component simply has a name property that we interpolate. $ctrl is the default controllerAs namespace, which is super nice because we don’t have to set it up.

We can now move the initialization work into the $onInit lifecycle hook, by defining the hook on the controller instance:

Okay great. But uhm… what’s the big deal? Well, while the resulting output will be the same, we now have the nice side effect that this component doesn’t do any initialization work when its constructor is called. Imagine we’d need to do some http requests during initialization of this component or controller. We’d need to take care of mocking these requests whenever we construct such a component. Now we have a better place for these kind of things