Course Progress 67%

Angular Reactive Forms

Angular Reactive Forms Angular में forms handle करने का सबसे powerful और scalable तरीका है। इसमें form की पूरी structure, validation और behavior component class में explicitly define की जाती है, जिससे forms predictable, testable और maintainable बनते हैं।

इस chapter में हम Reactive Forms को foundation से लेकर practical usage तक deep में समझेंगे, ताकि complex real-world forms confidently build किए जा सकें।

Reactive Forms क्या होती हैं

Reactive Forms में:

  • Form का model component class में define होता है
  • Template सिर्फ form को render करता है
  • Data flow one-way और explicit होता है
  • Form state fully observable होती है

यह approach Angular की reactive programming philosophy के साथ aligned है।

Required Module Setup

Reactive Forms use करने के लिए ReactiveFormsModule import करना जरूरी है।

import { Component } from '@angular/core';
import { ReactiveFormsModule, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-reactive-form',
  standalone: true,
  imports: [ReactiveFormsModule],
  templateUrl: './form.component.html'
})
export class ReactiveFormComponent {}

Standalone Angular में module component के imports में add किया जाता है।

Basic Reactive Form Example

सबसे पहले एक simple login form बनाते हैं।

Component Class

export class ReactiveFormComponent {

  loginForm = new FormGroup({
    username: new FormControl(''),
    password: new FormControl('')
  });

  onSubmit() {
    console.log(this.loginForm.value);
  }
}

Template

<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">

  <label>
    Username
    <input type="text" formControlName="username">
  </label>

  <label>
    Password
    <input type="password" formControlName="password">
  </label>

  <button type="submit">Login</button>

</form>

Key Concepts

  • FormGroup पूरा form represent करता है
  • FormControl individual input field
  • formGroup directive form को model से connect करता है
  • formControlName input को specific control से bind करता है

FormControl की State और Properties

हर FormControl ये states track करता है:

  • value
  • valid / invalid
  • touched / untouched
  • dirty / pristine
  • errors

Example:

this.loginForm.get('username')?.invalid

Validators in Reactive Forms

Reactive Forms में validators explicitly add किए जाते हैं।

Built-in Validators

import { Validators } from '@angular/forms';

loginForm = new FormGroup({
  username: new FormControl('', [Validators.required, Validators.minLength(3)]),
  password: new FormControl('', Validators.required)
});

Template में Validation Check

<div *ngIf="loginForm.get('username')?.invalid &&
            loginForm.get('username')?.touched">
  Username is required
</div>

FormBuilder का Use

Complex forms के लिए FormBuilder code को concise बनाता है।

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

constructor(private fb: FormBuilder) {}

form = this.fb.group({
  email: ['', [Validators.required, Validators.email]],
  password: ['', Validators.required]
});

FormBuilder recommended approach है large forms के लिए।

Nested FormGroups

Complex forms में nested groups common होते हैं।

profileForm = this.fb.group({
  name: [''],
  address: this.fb.group({
    city: [''],
    zip: ['']
  })
});

Form value structure:

{
  name: '',
  address: {
    city: '',
    zip: ''
  }
}

Updating Form Values

Reactive forms में values programmatically update की जा सकती हैं।

setValue

this.loginForm.setValue({
  username: 'admin',
  password: '1234'
});

patchValue

this.loginForm.patchValue({
  username: 'admin'
});

Difference:

  • setValue → सभी controls required
  • patchValue → partial update allowed

Enabling / Disabling Controls

this.loginForm.get('username')?.disable();
this.loginForm.get('username')?.enable();

यह feature dynamic forms में बहुत useful है।

Resetting Reactive Forms

this.loginForm.reset();

Reset करने पर:

  • Values clear
  • Validation reset
  • State pristine हो जाती है

Listening to Value Changes

Reactive forms observables expose करते हैं।

this.loginForm.valueChanges.subscribe(value => {
  console.log(value);
});

Individual control पर भी listen किया जा सकता है।

this.loginForm.get('username')?.valueChanges.subscribe();

Form Submission Flow

Reactive forms में submission controlled और predictable होती है।

onSubmit() {
  if (this.loginForm.valid) {
    // submit data
  }
}

Browser default submit behavior Angular handle करता है।

Reactive Forms vs Template-Driven Forms

High-level difference:

  • Reactive → explicit, scalable, testable
  • Template-Driven → simple, quick, implicit

Enterprise-level Angular apps में Reactive Forms preferred हैं।

Common Mistakes

  • ReactiveFormsModule import करना भूल जाना
  • FormControlName mismatch
  • Validation logic template में डाल देना
  • Direct DOM access करना

कब Reactive Forms use करें

Best scenarios:

  • Large forms
  • Dynamic fields
  • Complex validation logic
  • Enterprise applications
  • Unit testing heavy projects

Angular Reactive Forms Angular forms system की backbone हैं। अगले chapters में हम validation, custom validators और dynamic forms को deep level पर cover करेंगे, जिससे forms पूरी तरह production-ready बन सकें।