Junior From PDF Angular Angular

What is the difference between ngOnInit and constructor in Angular?

spect Constructor ngOnInit

Purpose Initializes the class Lifecycle hook, called after constructor

Use Case Inject

dependencies

Fetch data, initialize logic

Called By JavaScript engine Angular

Example:

constructor(private userService: UserService) {}

ngOnInit() {

this.userService.getUsers().subscribe(users => this.users =

users);

}

Real-Time Example:

In a profile component:

  • Use constructor to inject ProfileService
  • Use ngOnInit to fetch the user's data after initialization

More from Angular Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details