0%

angular-constructor-vs-ngoninit

Constructor vs ngOnInit

What’s the difference between constructor and ngOnInit in Angular?
constructor is a TypeScript class constructor while ngOnInit is an Angular lifecycle hook called by Angular to indicate that Angular is done creating the component. a common question is when to use constructor and when to use ngOnInit?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import {Component, OnInit} from '@angular/core';

@Component({
selector: 'app-product',
standalone: true,
imports: [],
templateUrl: './product.component.html',
styleUrl: './product.component.scss'
})
export class ProductComponent implements OnInit {
constructor() {
// What should be done here?
}

ngOnInit() {
// What should be done here?
}
}
  • constructor is used to initialize the class properties, but it’s not the right place to do any initialization that depends on Angular services or inputs. ngOnInit is the right place to do such initialization.
  • ngOnInit is an Angular lifecycle hook that is called after Angular has initialized all data-bound properties of a directive. It’s the right place to put initialization logic that depends on Angular services or inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import {Component, OnInit} from '@angular/core';
import {DataService} from "../data.service";

@Component({
selector: 'app-product',
standalone: true,
imports: [],
templateUrl: './product.component.html',
styleUrl: './product.component.scss'
})
export class ProductComponent implements OnInit {
private products: any[] = [];

// Dependency Injection goes here.
constructor(private dataService: DataService) {
// What should be done here?
}

ngOnInit() {
this.dataService.fetchData().subscribe((data: any) => {
this.products = data;
});
}
}

Conclusion

When to call Call count What to do Comments
constructor When create class 1 1. Initialize class properties, 2. DI
ngOnInit after constructor and the first ngOnChanges 1 1. Init @Input, 2. Call service to fetch data

References