Posted onEdited onInangular Symbols count in article: 267Reading time ≈1 mins.
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' }) exportclassProductComponentimplementsOnInit { 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.