Angular OnInit
Angular @OnInit is a lifecycle hook used to perform initialization work after Angular has initialized the component's data-bound properties.
What is @OnInit?
The ngOnInit() lifecycle hook is called once after Angular has initialized the component's input properties.
It is commonly used for initialization tasks such as loading data, preparing component properties, calling services, and setting up values required by the template.
Simple Definition
ngOnInit() is the place where we perform component initialization logic after Angular creates the component and initializes its bound properties.
Where @OnInit Fits in Angular Lifecycle
Basic Syntax
To use the OnInit lifecycle hook, implement the OnInit interface and define the ngOnInit() method.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-courses',
templateUrl: './courses.component.html'
})
export class CoursesComponent implements OnInit {
ngOnInit(): void {
console.log('Component initialized');
}
}
Important
Angular calls ngOnInit() automatically. We normally do not call it manually from the template.
Why Use @OnInit?
Load Data
Load course or application data when the component starts.
loadCourses()
Initialize Values
Set default values required by the component.
status = 'Active'
Service Calls
Start initial API or service related operations.
service.getData()
Prepare UI
Prepare component properties required by the template.
prepareDashboard()
1. Simple OnInit Example
The following example initializes a message when the component is created.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-welcome',
templateUrl: './welcome.component.html'
})
export class WelcomeComponent implements OnInit {
message = '';
ngOnInit(): void {
this.message = 'Welcome to CIIT Training Institute';
}
}
<h2>
{{ message }}
</h2>
Welcome to CIIT Training Institute
2. Initializing Component Properties
OnInit can be used to assign initial values to multiple component properties.
export class CourseDashboardComponent implements OnInit {
instituteName = '';
totalCourses = 0;
mode = '';
ngOnInit(): void {
this.instituteName = 'CIIT Training Institute';
this.totalCourses = 6;
this.mode = 'Online + Offline';
}
}
<h2>
{{ instituteName }}
</h2>
<p>
Total Courses:
{{ totalCourses }}
</p>
<p>
Training Mode:
{{ mode }}
</p>
CIIT Training Institute
Total Courses: 6
Training Mode: Online + Offline
3. Loading Initial Data
One common use of ngOnInit() is to prepare data that the template will display.
export class CoursesComponent implements OnInit {
courses: string[] = [];
ngOnInit(): void {
this.courses = [
'Java Full Stack',
'Python Full Stack',
'Full Stack .NET',
'Data Analytics'
];
}
}
<h3>Available Courses</h3>
<ul>
<li *ngFor="let course of courses">
{{ course }}
</li>
</ul>
How it works
Angular creates the component, calls ngOnInit(), initializes the courses array, and the template can then display the available courses.
4. Initializing Data from a Service
In real applications, ngOnInit() is often used to start an initial service call.
import { Component, OnInit } from '@angular/core';
import { CourseService } from './course.service';
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html'
})
export class CourseListComponent implements OnInit {
courses: any[] = [];
constructor(private courseService: CourseService) {
}
ngOnInit(): void {
this.courseService.getCourses()
.subscribe(data => {
this.courses = data;
});
}
}
Important Point
The constructor can receive the service dependency, while ngOnInit() can start the initialization operation.
@OnInit vs Constructor
| Constructor | ngOnInit() |
|---|---|
| Used mainly for dependency injection and basic setup. | Used for component initialization logic. |
| Runs when the class instance is created. | Runs during Angular's lifecycle initialization. |
| Angular lifecycle values may not be fully initialized. | Data-bound input properties are initialized. |
| Keep constructor logic simple. | Suitable for loading initial data and setup tasks. |
Lifecycle Execution Sequence
Complete CIIT Training Institute Example
Suppose CIIT Training Institute has a course dashboard. When the dashboard loads, we can initialize the institute name, course count, and available training modes using ngOnInit().
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-course-dashboard',
templateUrl: './course-dashboard.component.html'
})
export class CourseDashboardComponent implements OnInit {
instituteName = '';
courses: string[] = [];
trainingModes: string[] = [];
ngOnInit(): void {
this.instituteName = 'CIIT Training Institute';
this.courses = [
'Java Full Stack',
'Python Full Stack',
'Full Stack .NET',
'Data Analytics'
];
this.trainingModes = [
'Online',
'Offline'
];
}
}
<div>
<h2>
{{ instituteName }}
</h2>
<h4>
Available Courses
</h4>
<ul>
<li *ngFor="let course of courses">
{{ course }}
</li>
</ul>
<h4>
Training Modes
</h4>
<ul>
<li *ngFor="let mode of trainingModes">
{{ mode }}
</li>
</ul>
</div>
CIIT Training Institute
Available Courses
- Java Full Stack
- Python Full Stack
- Full Stack .NET
- Data Analytics
Training Modes
- Online
- Offline
Important Points About @OnInit
- ngOnInit() is called once for a component initialization cycle.
- It is commonly used for initialization logic.
- It is useful for preparing data required by the template.
- It can be used to start service or API operations.
- Avoid unnecessary heavy logic inside the constructor.
- Keep initialization code organized and easy to understand.
@OnInit Best Practices
- Use ngOnInit() for component initialization tasks.
- Keep constructor logic limited mainly to dependency injection.
- Use services for reusable business or API logic.
- Initialize only the values required by the component.
- Keep API and data loading logic readable.
- Avoid unnecessary repeated initialization operations.
Summary
Angular @OnInit provides the ngOnInit() lifecycle method for performing initialization work after Angular initializes the component's data-bound properties.
It is commonly used for setting initial values, preparing UI data, loading course information, and starting service or API operations.