Master Angular From Scratch

Learn Angular with clear, interactive, and structured lessons for beginners and developers.

ANGULAR COURSE SYLLABUS
1. Angular Introduction
Angular Introduction Angular History Angular Fundamentals Angular Architecture Component-Based Angular
2. Angular Setup
Angular Setup Introduction Installing Node.js Installing Angular CLI Creating an Angular Application Angular Project Structure
3. Components
Components Overview Component Anatomy Creating Components Component Selector Component Template Component Styles Component Metadata Standalone Components Parent and Child Components Reusable Components
4. Templates
Templates Introduction Template Syntax Template Expressions Template Statements Template Reference Variables ng-template ng-container ngTemplateOutlet Built-in Control Flow
5. Data Binding
Data Binding Introduction Interpolation Binding Property Binding Event Binding Two-Way Data Binding Class & Style Binding
6. Directives
Directives Introduction Attribute Directives Structural Directives Custom Directives
7. Pipes
Pipes Introduction Built-in Pipes Parameterized Pipes Chaining Pipes Custom Pipes
8. Event Handling
Event Handling Introduction DOM Events Event Binding Syntax Event Object Passing Data to Event Handlers
9. Input & Output
Component Communication @Input @Output EventEmitter
10. Lifecycle Hooks
Lifecycle Hooks Introduction ngOnInit ngOnChanges ngAfterViewInit ngOnDestroy
11. Services
Services Introduction Creating Angular Services Using Services in Components Sharing Data Through Services Service Scope
12. Dependency Injection
Dependency Injection Introduction Injecting Dependencies InjectionToken Provider Configuration
13. Routing
Routing Introduction Route Configuration RouterLink & Navigation Route Parameters Child Routes Route Guards
14. Forms
Angular Forms Introduction Template-Driven Forms Reactive Forms Form Validation Form Submission & Error Handling
15. HttpClient
HttpClient Introduction Configuring HttpClient GET Request POST, PUT & DELETE Requests Headers & Parameters HTTP Error Handling
16. Observables
Observables Introduction Creating & Subscribing to Observables Observable Data Streams Observable Operators Subscription Management
17. RxJS
RxJS Introduction RxJS Operators Transformation & Filtering Combining Observables Higher-Order Mapping Subjects
18. API Integration
API Integration Introduction Connecting Angular with REST API Consuming API Data CRUD API Integration API Response & Error Handling

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

Component Created Angular creates component
→
Inputs Initialized Bound values become available
→
ngOnInit() Initialization logic runs
→
Component Ready UI continues rendering

Basic Syntax

To use the OnInit lifecycle hook, implement the OnInit interface and define the ngOnInit() method.

Component
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.

Component
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';

    }

}
Template
<h2>
    {{ message }}
</h2>
Expected Output:

Welcome to CIIT Training Institute

2. Initializing Component Properties

OnInit can be used to assign initial values to multiple component properties.

Component
export class CourseDashboardComponent implements OnInit {

    instituteName = '';
    totalCourses = 0;
    mode = '';

    ngOnInit(): void {

        this.instituteName = 'CIIT Training Institute';

        this.totalCourses = 6;

        this.mode = 'Online + Offline';

    }

}
Template
<h2>
    {{ instituteName }}
</h2>

<p>
    Total Courses:
    {{ totalCourses }}
</p>

<p>
    Training Mode:
    {{ mode }}
</p>
Expected Output:

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.

Component
export class CoursesComponent implements OnInit {

    courses: string[] = [];

    ngOnInit(): void {

        this.courses = [
            'Java Full Stack',
            'Python Full Stack',
            'Full Stack .NET',
            'Data Analytics'
        ];

    }

}
Template
<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.

Component
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

1. Create Component Angular creates the component instance
→
2. Initialize Inputs Input properties are initialized
→
3. ngOnInit() Initialization logic executes
→
4. Continue Lifecycle Angular continues processing the component

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().

course-dashboard.component.ts
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'
        ];

    }

}
course-dashboard.component.html
<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>
Expected Output:

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.