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

Angular Constructor vs ngOnInit – Interview Questions

Q 1: What is Constructor?

Ans: Used for dependency injection and class initialization.

Q 2: What is ngOnInit?

Ans: Lifecycle hook executed after component initialization.

Q 3: Where should API calls be placed?

Ans: Inside ngOnInit.

Q 4: Can logic be written in constructor?

Ans: Only basic initialization logic.

Q 5: Why avoid heavy logic in constructor?

Ans: Because component inputs are not yet initialized.

Angular Constructor vs ngOnInit – Objective Questions (MCQs)

Q1. Constructor is mainly used for:






Q2. ngOnInit() is used for:






Q3. Constructor executes:






Q4. ngOnInit is part of:






Q5. Best place for API calls is: