Sitemap

What’s to Angular’s lifecycle hooks and inputs default values?

2 min readDec 27, 2018

Passing inputs to an angular component is always fun. We tell the component which variable we want to pass and puff like magic it just works.

But do we really know what to expect in our input variable with every lifecycle hook? What if our component input has a default value? What if the container component is passing an input it gets as an input?

Let’s try to make some sense of it and learn how to avoid bugs with this little experiment.

We’ve got our app component:

my-app component holds two components, my-container which just wraps my-inputs and pass an input to it and my-inputs:

namedefault

This is where the magic happens.

We’ve got name as our input and we subscribe to ngOnInit, ngOnChanges, ngOnDestroy and the constructor to save the value of the input at the moment of the lifecycle-hook.

One final piece, my-container code:

Just before we run the code and reveal the results, let’s take a moment to recap what we have done here.

We have my-inputs component that has a single input name with a default value of ‘default’. We’re saving name’s value at the constructor and then on every lifecycle hook — Later to be printed.

Also we have my-container which is passing name input without any value on creation, then later changes the value to ‘eden’.

Running our application:

The results

Cool! What does it mean?

Well, rendering my-inputs directly without a container, shows that in the component constructor the value if name is the default value we set. Only the ngOnInit lifecycle hook is called afterwards and the value isn’t changed.

In the second case — rendering my-container, shows that in my-inputs constructor is the default value set. Surprisingly ngOnChanges is called with an empty value that overrides the default value even though it was not intentional. Therefore ngOnInit is called with an empty value unlike it did when my-inputs was rendered directly and finally changes to eden with the input is changed with setTimeout.

Learning from this experiment, we can conclude that

Setting a default value to a component input doesn’t prevent it being override with an empty value from it’s container.

It’s safe to say that most cases will be fine, however if input passing is an asynchronous operation like we see here with setTimeout, it is best to validate the component inputs rather than to expect a valid value from the container.

Repository: https://github.com/edenpessach/angular-inputs-lifecycle

StackBlitz: https://stackblitz.com/edit/angular-inputs-lifecycle?file=src%2Fapp%2Fcontainer%2Fcontainer.component.ts

--

--

Eden Pessach
Eden Pessach

Written by Eden Pessach

Front end pioneer and ping pong trainee @ Datorama

Responses (1)