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:
- Initialize class-level variables.
- Inject dependencies (Services).
- 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()?
- You want to call APIs
- You need to access @Input() values
- You need lifecycle-based logic
- 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
- Best for API calls
- Best for initialization logic
- 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 |