The OnInit interface and lifecycle hooks

In software engineering, the term life cycle is often used to symbolize a list of sequential steps marking the various phases of any given item, starting from the first relevant one and ending up with the last. Depending on the given context, the item can either be a project, an application, a thread, and so on. Different kinds of items can also have different relevant phases worth measuring. For example, in Object-Oriented Programming languages, the item is often an object, and the lifecycle marks the steps from its creation phase (usually issued by constructors, initializers, or builders) up to its destruction phase (usually handled by destructors, dispose statements, garbage collections, and so on).

Most modern frameworks, including .NET Core and Angular, manage their objects through a known and measurable life cycle; on top of that, they also provide a number of lifecycle hooks bound to the most relevant steps that can be used by developers to perform actions whenever they occur.

In Angular, each component is subject to a life cycle; the framework creates it, renders it, creates and renders its children, checks it when its data-bound properties change, and eventually, destroys and removes it from the DOM; most of these steps are bound to a dedicated lifecycle hook, as we can see in the following overview:

It's important to understand that each lifecycle hook, in addition to being exposed to the developers, is also used in the Angular framework to perform required internal tasks.

With regard to the preceding diagram, the non-indented hooks are available for component and directive instances, while the indented ones are for component instances only. The reason is fairly obvious--directives don't have contents and views that can trigger them.

This is good to know, but what about our binding problem? What does this have to do with it? We can easily answer that by taking a look at the Angular official documentation and reading what happens during the ngOnInit lifecycle hook:

ngOnInit(): Initializes the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties. These are called once, after the first ngOnChanges().

Here lies our answer--we are expecting to get our @Input class value within the constructor, but the framework will only set it during the ngOnInit() lifecycle hook, which comes later on. This means that our code is fine, except that we chose the wrong hook.

For a detailed description of all the available Angular lifecycle hooks, you can check out the following URL from the official docs:

https://angular.io/guide/lifecycle-hooks
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.225