Harry
Harry

Reputation: 75

Why data initialization should not be done in the constructor of the component in Angular?

I am new to Angular 6. I have a requirement that I need to initialize all the drop-down fields through API calls. Many developers suggest that api calls for the data initialization should be done inside the ngOninit rather than doing it through constructor? Can anyone please let me know the reason behind this ?

Upvotes: 2

Views: 2077

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

constructor method on a class (or TypeScript in this case) is a feature of a class itself, rather than an Angular feature. It’s out of Angular’s control when the constructor is invoked

constructor invoke when the new instant of the class created but this doesn't mean angular finish finalized the component and binding

import { Component, OnInit } from '@angular/core';

@Component({})
class ExampleComponent implements OnInit {
  constructor() {}

  // called on demand by Angular
  ngOnInit() {
    console.log('ngOnInit fired');
  }
}

const instance = new ExampleComponent();

// Angular calls this when necessary
instance.ngOnInit();

Note that JavaScript engine calls the constructor, not Angular directly. Which is why the ngOnInit (and $onInit in AngularJS) lifecycle hook was created.

ngOnInit is purely there to give us a signal that Angular has finished initialising the component.

This phase includes the first pass at Change Detection against the properties that we may bind to the component itself - such as using an @Input() decorator.

Due to this, the @Input() properties are available inside ngOnInit, however are undefined inside the constructor

The ngOnInit lifecycle hook is a guarantee that your bindings are readily available.

from doc

Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties. Called once, after the first ngOnChanges().

Lifecycle sequence

  1. ngOnChanges()
  2. ngOnInit()
  3. ngDoCheck()
  4. ngAfterContentInit()
  5. ngAfterContentChecked()
  6. ngAfterViewInit()
  7. ngAfterViewChecked()

toddmotto - Angular constructor versus ngOnInit

The essential difference between Constructor and ngOnInit in Angular

Upvotes: 1

Sarthak Aggarwal
Sarthak Aggarwal

Reputation: 2312

This is because the constructor is called to initialize the class and not the component. The constructor is called before ngOnInit , at this point the component hasn’t been created yet, only the component class has being instantiated thus your dependencies are brought in, but your initialization code will not run.

To ensure your initialization code runs, simply put it in the ngOnInit which is the lifecycle hook method of a component in angular ensuring that the component has been created successfully.

Upvotes: 3

Related Questions