What is ngOnInit in Angular: Explanation and Example
ngOnInit is a lifecycle hook in Angular that runs once after the component's data-bound properties are initialized. It is used to perform component initialization tasks like fetching data or setting up state before the view appears.How It Works
Think of ngOnInit as a special moment when your Angular component is ready to start working but just before it shows anything on the screen. It runs once after Angular sets up the component's input properties. This is like preparing your tools before starting a project.
Imagine you are baking a cake. You gather all ingredients and mix them before putting the cake in the oven. Similarly, ngOnInit lets you prepare data or start processes before the user sees the component. It helps keep your component organized and ready.
Example
This example shows a simple Angular component that uses ngOnInit to set a welcome message when the component starts.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-welcome', template: `<h1>{{ message }}</h1>` }) export class WelcomeComponent implements OnInit { message = ''; ngOnInit() { this.message = 'Hello! Welcome to Angular.'; } }
When to Use
Use ngOnInit when you need to run code right after your component is created and its inputs are ready. Common uses include:
- Fetching data from a server to display
- Setting initial values for variables
- Starting timers or subscriptions
This ensures your component is fully prepared before the user interacts with it.
Key Points
ngOnInitruns once after component inputs are set.- It is part of Angular's lifecycle hooks.
- Use it for initialization tasks, not for DOM manipulation.
- Helps keep component setup clean and predictable.
Key Takeaways
ngOnInit is the place to put initialization code after inputs are ready.ngOnInit instead.