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 Reactive Forms

Learn how to create and manage Angular forms programmatically using FormControl, FormGroup, FormBuilder and Validators.

What are Reactive Forms?

Reactive Forms provide a programmatic approach to creating and managing Angular forms.

The form model is created in the component using objects such as FormControl and FormGroup.

Reactive forms are especially useful when an application needs complex validation, dynamic controls or precise control over form state.

Reactive Form Flow

Component Define Form Model
→
FormGroup Group Controls
→
Validation Check Values
→
Template Display Form

Main Reactive Form Concepts

C
FormControl

Represents a single form field and its state.

G
FormGroup

Groups multiple controls into a form model.

B
FormBuilder

Provides a convenient way to create form controls and groups.

V
Validators

Apply validation rules to form controls.

Import ReactiveFormsModule

Reactive forms use Angular's ReactiveFormsModule.

In a standalone component, the module can be included in the component's imports array.

Standalone Component
import { Component } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';

@Component({
    selector: 'app-registration',
    imports: [ReactiveFormsModule],
    templateUrl: './registration.component.html'
})
export class RegistrationComponent {

}

Creating FormControl

FormControl represents one individual form field.

It stores the field value and tracks states such as valid, invalid, touched and dirty.

Example
name = new FormControl('');
Initial Value
name = new FormControl('CIIT Training Institute');

Creating FormGroup

FormGroup combines multiple FormControls into a single form model.

It allows related fields to be managed together.

Example
registrationForm = new FormGroup({

    name: new FormControl(''),

    email: new FormControl(''),

    mobile: new FormControl(''),

    course: new FormControl('')

});

Connecting FormGroup with Template

The formGroup directive connects the HTML form with the FormGroup created in TypeScript.

Individual controls are connected using formControlName.

HTML Template
<form [formGroup]="registrationForm">

    <input
        type="text"
        formControlName="name">

    <input
        type="email"
        formControlName="email">

    <input
        type="text"
        formControlName="mobile">

    <select formControlName="course">

        <option value="">
            Select Course
        </option>

        <option value="Java Full Stack">
            Java Full Stack
        </option>

        <option value=".NET Full Stack">
            .NET Full Stack
        </option>

    </select>

</form>

Using FormBuilder

FormBuilder provides helper methods that make creating reactive form controls and groups more concise.

It is useful when a form contains multiple controls.

FormBuilder Example
import { Component } from '@angular/core';
import {
    FormBuilder,
    Validators
} from '@angular/forms';

@Component({
    selector: 'app-enquiry',
    templateUrl: './enquiry.component.html'
})
export class EnquiryComponent {

    enquiryForm = this.fb.group({

        name: [''],

        email: [''],

        mobile: [''],

        course: ['']

    });

    constructor(
        private fb: FormBuilder
    ) {
    }

}

Using Validators

Angular provides built-in validators that can be attached to reactive form controls.

Examples include required, email, minLength and maxLength.

Validators Example
registrationForm = new FormGroup({

    name: new FormControl(
        '',
        Validators.required
    ),

    email: new FormControl(
        '',
        [
            Validators.required,
            Validators.email
        ]
    )

});

Multiple Validators

Example
mobile = new FormControl(
    '',
    [
        Validators.required,
        Validators.minLength(10),
        Validators.maxLength(10)
    ]
);

Mobile Validation

The mobile field is required and must contain the expected number of characters.

CIIT Training Institute Example

Suppose CIIT Training Institute has a registration form for visitors interested in a technical course.

Reactive Forms can define the complete form structure and validation rules inside the component.

Component
import { Component } from '@angular/core';
import {
    FormBuilder,
    Validators
} from '@angular/forms';

@Component({
    selector: 'app-course-registration',
    templateUrl: './course-registration.component.html'
})
export class CourseRegistrationComponent {

    registrationForm = this.fb.group({

        name: [
            '',
            Validators.required
        ],

        email: [
            '',
            [
                Validators.required,
                Validators.email
            ]
        ],

        mobile: [
            '',
            [
                Validators.required,
                Validators.minLength(10),
                Validators.maxLength(10)
            ]
        ],

        course: [
            '',
            Validators.required
        ]

    });

    constructor(
        private fb: FormBuilder
    ) {
    }

    submitForm() {

        if (this.registrationForm.valid) {

            console.log(
                this.registrationForm.value
            );

        }

    }

}
Template
<form
    [formGroup]="registrationForm"
    (ngSubmit)="submitForm()">


    <label>
        Name
    </label>

    <input
        type="text"
        formControlName="name">


    <label>
        Email
    </label>

    <input
        type="email"
        formControlName="email">


    <label>
        Mobile
    </label>

    <input
        type="text"
        formControlName="mobile">


    <label>
        Course
    </label>

    <select
        formControlName="course">

        <option value="">
            Select Course
        </option>

        <option value="Java Full Stack">
            Java Full Stack
        </option>

        <option value=".NET Full Stack">
            .NET Full Stack
        </option>

        <option value="Python Full Stack">
            Python Full Stack
        </option>

    </select>


    <button
        type="submit"
        [disabled]="registrationForm.invalid">

        Register

    </button>

</form>

CIIT Training Institute Registration

Name: Required

Email: Valid Email Required

Mobile: 10 Characters Required

Course: Select Course

Reading Form Values

Reactive form values can be accessed through the value property of the FormGroup.

This is useful when form data needs to be processed or sent to another service.

Example
console.log(
    this.registrationForm.value
);
Reading a Specific Control
console.log(
    this.registrationForm.get('email')?.value
);

Checking Form Status

Component
if (this.registrationForm.valid) {

    console.log('Form is valid');

}

if (this.registrationForm.invalid) {

    console.log('Form is invalid');

}

Displaying Validation Messages

Validation messages can be displayed by checking the control's validation state.

A common pattern is to display a message after the user has interacted with the control.

Template
<input
    type="email"
    formControlName="email">


<div
    *ngIf="
        registrationForm.get('email')?.invalid &&
        registrationForm.get('email')?.touched
    ">

    Please enter a valid email address.

</div>

Accessing a FormControl

Component
get emailControl() {

    return this.registrationForm.get('email');

}
Template
<div
    *ngIf="emailControl?.invalid &&
           emailControl?.touched">

    Please enter a valid email.

</div>

Resetting a Reactive Form

The reset() method can be used to reset the form values and state.

This is useful after a successful submission or when the user wants to clear the form.

Example
this.registrationForm.reset();

Enable and Disable Controls

Disable Control
this.registrationForm
    .get('email')
    ?.disable();
Enable Control
this.registrationForm
    .get('email')
    ?.enable();

Dynamic Validation

Reactive forms make it possible to change validators programmatically when application requirements change.

This is one of the reasons reactive forms are useful for complex form scenarios.

Example
const mobileControl =
    this.registrationForm.get('mobile');

mobileControl?.setValidators([
    Validators.required,
    Validators.minLength(10)
]);

mobileControl?.updateValueAndValidity();

Reactive Form Features

M
Explicit Model

Form structure is defined in TypeScript.

V
Validation

Validators can be defined programmatically.

D
Dynamic Forms

Controls and validators can be changed dynamically.

S
State Tracking

Form and control states can be inspected directly.

Reactive Forms vs Template-driven Forms

Feature Reactive Forms Template-driven Forms
Form Model Explicitly defined in TypeScript Primarily represented in the template
FormControl Directly used Managed through directives
Validation Programmatic Template-oriented
Dynamic Controls Convenient for complex scenarios Less convenient for complex scenarios
Typical Use Complex and dynamic forms Simpler forms

Important Points

1. Form Model is Created in TypeScript

Reactive forms define the form structure explicitly inside the component.

2. Use FormControl and FormGroup

Use FormControl for individual fields and FormGroup for a collection of controls.

3. Validators Can Be Programmatic

Validation rules can be attached directly to reactive form controls.

4. Useful for Complex Forms

Reactive forms are suitable when a form requires advanced validation or dynamic behavior.

Reactive Forms Best Practices

  • Keep the form model clearly defined in the component.
  • Use meaningful names for controls and groups.
  • Add appropriate validators to important fields.
  • Check form validity before processing submitted data.
  • Keep complex form-related logic in TypeScript instead of placing unnecessary logic in the template.
  • Use reactive forms when dynamic controls or complex validation are required.

Summary

Reactive Forms provide a programmatic way to create, validate and manage Angular forms.

Important building blocks include FormControl, FormGroup, FormBuilder and Validators.

Reactive forms are especially useful for forms that require explicit form models, advanced validation or dynamic behavior. In the next topic, we will learn about Form Validation.