Junior
From PDF
Angular
Angular
What is the difference between ngOnInit and constructor in Angular?
Short answer: Aspect 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 code
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
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png