Angular Constructor vs ngOnInit

If you are confused about Constructor vs ngOnInit, then I will explain in a very easy way.

What is a Constructor in Angular?

The constructor is a feature of a TypeScript class. it’s not a part of Angular.

It is used to:

  1. Initialize class-level variables.
  2. Inject dependencies (Services).
  3. Set up basic values before Angular starts rendering the component.

Note: Angular only calls the constructor once when the component is created.

Example (Angular 17+ version):


export class AppComponent {
  constructor(private userService: UserService) {
    console.log('Constructor called!');
  }
}

Note: It is best for dependency injection.

What is ngOnInit() in Angular?

ngOnInit() is a lifecycle hook provided by Angular.

It runs after the constructor.

When we use ngOnInit()?

  1. You want to call APIs
  2. You need to access @Input() values
  3. You need lifecycle-based logic
  4. You want to run code once after component initialization

Example (Angular 17+)


export class AppComponent implements OnInit {
  ngOnInit() {
    console.log('ngOnInit called!');
  }
}

Best use of ngOnInit

  1. Best for API calls
  2. Best for initialization logic
  3. Best for using @Input() values

Constructor vs ngOnInit – Key Differences

Feature Constructor ngOnInit
Part of TypeScript Angular lifecycle
When it runs Immediately when class is created After constructor & after data bindings
Use cases Dependency Injection API calls, business logic
Access @Input() ❌ Not safe ✔ Safe
Multiple calls Called once Called once
Should contain heavy logic? ❌ No ✔ Yes
Component is fully loaded? ❌ No ✔ Yes