Angular: ngOnInit and Constructor.

Angular: ngOnInit and Constructor.

When I was starting with the Angular Framework, I didn't know the purpose of these two methods, but after studying and practicing it became clear why the two exist and their main differences, so let's understand more about that.

Constructor

It is a feature of the class, which comes with TypeScript, itself. Allows us to work with Dependency Injection (DI).

How does Angular DI happen? See the example below:

 constructor(private route: ActivatedRoute) {

    this.product= this.route.snapshot.data['product'];
  }

A dependency on the Angular Router or ActivatedRoute was injected into the constructor, which provides us with access to information about a route associated with a loaded component.

The constructor is used to initialize the class members, that is inject dependencies into the component. Always remember that it is a characteristic of the class itself, which comes from TypeScript, does not belong to Angular.

ngOnInit()

NgOnInit is part of the component's life cycle, in the documentation you will find detailed explanations in Component Lifecycle. Yes, the framework has a life cycle for each component we create!

When ngOnInit () is called by the framework it indicates that the component initialization has been completed, and within OnInit we can then include logic, rules and call other functions that we have in our component. See the example below, where we have DI in the constructor and the logic inside ngOnInit, and will see that OnInit is part of the angular/core:

import { ProductService } from './../product.service';
import { Product } from './../product.model';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product-read',
  templateUrl: './product-read.component.html',
  styleUrls: ['./product-read.component.css']
})
export class ProductReadComponent implements OnInit {

  products: Product[]
  displayedColumns = ['id', 'name', 'price', 'action']

  constructor(private productService: ProductService) { }

  ngOnInit(): void {
    this.productService.read().subscribe(products => {
      this.products = products
    })
  }

In the example above, that we are injecting a service dependency into the component, then we implement the logic inside OnInit.

But how work this component life cycle work?

Before OnInit is called, two things happen. It starts only after Angular finishes creating the DOM, also after executing the constructor and after the first ngOnChanges (it is also part of the component's life cycle). When the framework ends these processes, we have ngOnInit () in action. The constructor is initialized first, because if we have dependencies on other classes, we will need them.

Responsibilities

It is important to understand and know how to work correctly with these two methods. So it is important not to overload the constructor with things that do not involve dependency injections, just leave it for that purpose. Keeping it simple makes it easier to load DI's correctly into the component class, prevents bugs from occurring, and makes unit testing easier. See the illustration below, showing the life cycle of a component:

Follow us @reaygreatsite.png

Conclusion

We can understand that each method its purpose very well defined. It may seem confusing when we are starting, but after studying and practicing you will see that it is easy to visualize the behavior and responsibility of each of them.

If you still have questions about the main differences, I suggest taking a look at these articles that explain very well too, in addition to Angular's own documentation:

Link: ultimatecourses.com/blog/exploring-angular-..

Link: angular.io/guide/lifecycle-hooks

Link: stackoverflow.com/questions/35763730/differ..

If you want to contribute with some information for this post, leave a comment, thanks for reading, see you in the next post! ๐Ÿ˜‰

ย