What is ngOnInit() in Angular?
1. What is ngOnInit()?
ngOnInit() is an Angular lifecycle hook that runs once after Angular initializes a component's input properties.
It is commonly used to perform component initialization logic, such as:
- Loading initial data
- Calling a service/API
- Setting initial values
- Performing setup that depends on
@Input()values
ngOnInit() comes from Angular's OnInit interface.
import { Component, OnInit } from '@angular/core';
export class Product implements OnInit {
ngOnInit(): void {
console.log('Component initialized');
}
}
2. Why do we need ngOnInit()?
When Angular creates a component, we often need to execute some logic after Angular has initialized the component.
For example, suppose a ProductList component needs to load products from an ASP.NET Core Web API.
We don't want the template itself to be responsible for loading the data.
Instead:
Component created
↓
Constructor runs
↓
Angular initializes inputs
↓
ngOnInit()
↓
Call ProductService
↓
Call Web API
↓
Receive products
↓
Display products
So ngOnInit() provides a standard place for initialization logic.
3. Full Simple Sample Program
Suppose our Angular application needs to display products.
product.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ProductService {
getProducts(): string[] {
return [
'Laptop',
'Keyboard',
'Mouse'
];
}
}
product.ts
import { Component, OnInit, inject } from '@angular/core';
import { ProductService } from './product.service';
@Component({
selector: 'app-product',
standalone: true,
templateUrl: './product.html'
})
export class Product implements OnInit {
private productService = inject(ProductService);
products: string[] = [];
ngOnInit(): void {
this.products = this.productService.getProducts();
}
}
product.html
<h2>Products</h2>
<ul>
@for (product of products; track product) {
<li>{{ product }}</li>
}
</ul>
Output
Products
Laptop
Keyboard
Mouse
4. Program Explanation
Step 1 — Angular creates the component
Angular creates an instance of:
Product
Step 2 — Service is injected
private productService = inject(ProductService);
Angular's Dependency Injection system provides the ProductService.
Step 3 — products starts empty
products: string[] = [];
Initially:
products = []
Step 4 — Angular calls ngOnInit()
ngOnInit(): void {
this.products = this.productService.getProducts();
}
The component gets the products from the service.
Now:
products =
[
"Laptop",
"Keyboard",
"Mouse"
]
Step 5 — Template displays the products
@for (product of products; track product) {
<li>{{ product }}</li>
}
Angular renders the products on the page.
5. OnInit vs ngOnInit()
These two are related but not the same thing.
OnInit
OnInit is a TypeScript interface provided by Angular.
export class Product implements OnInit
It tells TypeScript that the class should implement:
ngOnInit()
ngOnInit()
This is the actual lifecycle hook method:
ngOnInit(): void {
console.log('Initialized');
}
So:
OnInit
↓
Interface
ngOnInit()
↓
Lifecycle hook method
6. Is implements OnInit mandatory?
No.
This works:
export class Product {
ngOnInit(): void {
console.log('Initialized');
}
}
Angular recognizes and calls ngOnInit() based on the lifecycle method.
However, using:
implements OnInit
is recommended because TypeScript can check that you've implemented the interface correctly.
For example:
export class Product implements OnInit {
ngOnInit(): void {
}
}
is clearer and safer.
7. Constructor vs ngOnInit()
This is a very important Angular interview question.
| Constructor | ngOnInit() |
|---|---|
| TypeScript/JavaScript class feature | Angular lifecycle hook |
| Runs when the class instance is created | Runs during Angular component initialization |
| Good for basic class setup | Good for Angular initialization logic |
| Dependency injection can happen here | Often used for initial data loading |
| Inputs are not yet initialized when constructor runs | Input properties have been initialized |
Runs before ngOnInit() |
Runs after constructor |
Example:
export class Product implements OnInit {
constructor() {
console.log('Constructor');
}
ngOnInit(): void {
console.log('ngOnInit');
}
}
Output:
Constructor
ngOnInit
A useful rule is:
constructor
↓
Create the object / inject dependencies
ngOnInit
↓
Initialize the component
With modern Angular, dependencies may also be obtained with inject() as in the full example above.
8. ngOnInit() with @Input()
One important reason for using ngOnInit() is that Angular has initialized input properties before it calls ngOnInit().
For example:
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-user',
standalone: true,
template: `<h2>{{ name }}</h2>`
})
export class User implements OnInit {
@Input() name = '';
ngOnInit(): void {
console.log(this.name);
}
}
If the parent sends:
<app-user name="Syed"></app-user>
Angular initializes:
name = "Syed"
before calling:
ngOnInit()
So the basic lifecycle is:
Constructor
↓
Angular sets @Input() values
↓
ngOnChanges() // when applicable
↓
ngOnInit()
9. Advantages
1. Clear initialization location
Initialization logic is kept in a predictable place.
ngOnInit(): void {
this.loadProducts();
}
2. Input properties are initialized
You can access initialized input values.
3. Good separation of responsibilities
Constructor can focus on object creation/dependency setup while ngOnInit() handles Angular initialization.
4. Easy to understand
Other developers immediately know:
ngOnInit()
contains initialization logic.
5. Runs only once
It is useful for logic that should execute once when the component is initialized.
10. Disadvantages / Things to Watch
ngOnInit() itself doesn't have major disadvantages, but there are some considerations.
1. Don't put too much logic inside it
Avoid:
ngOnInit(): void {
// 200 lines of business logic
}
Prefer:
ngOnInit(): void {
this.loadProducts();
}
and move reusable/business logic into services.
2. It runs only once
If an @Input() value changes later, ngOnInit() will not run again.
For reacting to changing inputs, depending on the design, you may use mechanisms such as:
ngOnChanges()
or modern signal-based reactive APIs.
11. Key Points
ngOnInit()is an Angular lifecycle hook.- It belongs to the
OnInitlifecycle interface. - It runs once per component instance.
- It runs after Angular initializes the component's input properties.
- The constructor runs before
ngOnInit(). - It is commonly used for initialization and initial data loading.
implements OnInitis recommended for type checking and clarity.- Don't place large amounts of business logic directly inside
ngOnInit(). - If an input changes later,
ngOnInit()doesn't run again. ngOnInit()works with both standalone and NgModule-based Angular components.
12. Interview Questions and Answers
Q1. What is ngOnInit()?
ngOnInit() is an Angular lifecycle hook that runs once after Angular initializes the component's input properties. It is commonly used for component initialization and initial data loading.
Q2. How many times does ngOnInit() execute?
Normally once for each component instance.
Q3. Which runs first: constructor or ngOnInit()?
The constructor runs first.
constructor
↓
ngOnInit
Q4. What is the difference between OnInit and ngOnInit()?
OnInit is an Angular lifecycle interface.
implements OnInit
ngOnInit() is the lifecycle method defined by that interface.
ngOnInit(): void {
}
Q5. Is implements OnInit mandatory?
No. Angular can still call a correctly named ngOnInit() method. However, implementing OnInit is recommended because it provides compile-time checking and makes the lifecycle contract explicit.
Q6. Can we call an API from ngOnInit()?
Yes. Initial data loading is one of its common uses.
ngOnInit(): void {
this.loadProducts();
}
Q7. Can we access @Input() values inside ngOnInit()?
Yes. Angular has initialized input values before ngOnInit() executes.
Q8. Does ngOnInit() execute again when an @Input() changes?
No. ngOnInit() runs once for that component instance. For subsequent input changes, ngOnChanges() or reactive signal-based patterns may be appropriate.
Q9. Constructor or ngOnInit() — where should initialization logic go?
Use the constructor primarily for class construction/dependency setup. Use ngOnInit() for Angular-specific component initialization, especially logic that depends on initialized inputs.
Interview one-line answer
ngOnInit()is an Angular lifecycle hook that executes once after Angular initializes a component's input properties and is commonly used for component initialization and initial data loading.