Course Progress 72%

Angular Dynamic Forms

Angular Dynamic Forms का मतलब है ऐसे forms बनाना जिनकी structure, fields, validation और behavior runtime पर change हो सके। Real-world applications में अक्सर forms static नहीं होते, बल्कि user actions, configuration, API response या business rules के आधार पर dynamically create और update होते हैं।

इस chapter में हम Angular Dynamic Forms को Reactive Forms के perspective से deep में समझेंगे, क्योंकि dynamic behavior के लिए Reactive Forms सबसे powerful और flexible approach है।

Dynamic Forms क्या होते हैं

Dynamic Forms में:

  • Form fields runtime पर add या remove होते हैं
  • Validation dynamically apply या change होती है
  • Form structure code से generate होती है
  • Same form multiple use-cases handle करता है

Angular Dynamic Forms mostly data-driven होते हैं।

Reactive Forms क्यों जरूरी हैं

Template-driven forms dynamic scenarios में limit हो जाते हैं।

Dynamic forms के लिए Reactive Forms preferred हैं क्योंकि:

  • Form structure explicit होती है
  • Controls programmatically manage किए जा सकते हैं
  • Validation runtime पर update की जा सकती है
  • Form state predictable रहती है

इस chapter के सभी examples Reactive Forms पर based हैं।

Core Building Blocks

Dynamic forms समझने के लिए ये concepts clear होने चाहिए:

  • FormGroup
  • FormControl
  • FormArray
  • Validators
  • Runtime control management

FormArray का Role

FormArray dynamic forms का सबसे important building block है।

FormArray:

  • Multiple similar controls को manage करता है
  • Add / remove operations support करता है
  • Lists और repeatable fields के लिए ideal है

Basic FormArray Example

मान लेते हैं user multiple phone numbers add कर सकता है।

Component Class

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

export class DynamicFormComponent {

  form = this.fb.group({
    phones: this.fb.array([])
  });

  constructor(private fb: FormBuilder) {}

  get phones() {
    return this.form.get('phones') as FormArray;
  }

  addPhone() {
    this.phones.push(
      this.fb.control('', Validators.required)
    );
  }

  removePhone(index: number) {
    this.phones.removeAt(index);
  }
}

Template

<form [formGroup]="form">

  <div formArrayName="phones">
    <div *ngFor="let phone of phones.controls; let i = index">
      <input [formControlName]="i">
      <button type="button" (click)="removePhone(i)">Remove</button>
    </div>
  </div>

  <button type="button" (click)="addPhone()">Add Phone</button>

</form>

यह form runtime पर fields add/remove करता है।

Dynamic FormControl Creation

Controls condition के आधार पर add किए जा सकते हैं।

if (this.isCompanyUser) {
  this.form.addControl(
    'companyName',
    this.fb.control('', Validators.required)
  );
}

Remove करने के लिए:

this.form.removeControl('companyName');

यह pattern role-based forms में बहुत common है।

Dynamic FormGroup Creation

Nested dynamic groups भी create किए जा सकते हैं।

this.form.addControl(
  'address',
  this.fb.group({
    city: [''],
    zip: ['']
  })
);

Complex forms में यह approach structure clean रखता है।

Data-Driven Dynamic Forms

Real projects में form structure अक्सर JSON config से आती है।

Example config:

fields = [
  { name: 'email', type: 'email', required: true },
  { name: 'age', type: 'number', required: false }
];

Form build logic:

buildForm() {
  const group: any = {};

  this.fields.forEach(field => {
    group[field.name] = this.fb.control(
      '',
      field.required ? Validators.required : []
    );
  });

  this.form = this.fb.group(group);
}

यह approach CMS और admin panels में widely used है।

Dynamic Validation Management

Validators runtime पर change किए जा सकते हैं।

const control = this.form.get('email');

control?.setValidators([Validators.required, Validators.email]);
control?.updateValueAndValidity();

Remove validators:

control?.clearValidators();
control?.updateValueAndValidity();

यह step अक्सर भूल जाता है, जिससे validation apply नहीं होती।

Conditional Fields और Visibility

Dynamic forms में field visibility common requirement है।

this.form.get('userType')?.valueChanges.subscribe(type => {
  if (type === 'admin') {
    this.form.addControl('adminCode', this.fb.control(''));
  } else {
    this.form.removeControl('adminCode');
  }
});

Field visibility हमेशा form structure से sync रहनी चाहिए।

Dynamic Forms और Validation Messages

Dynamic fields के लिए generic error handling जरूरी है।

<div *ngIf="control.invalid && control.touched">
  Invalid value
</div>

Hard-coded error messages avoid करें।

Dynamic Forms Submission

Dynamic forms submission normal reactive form जैसा ही होता है।

onSubmit() {
  if (this.form.valid) {
    console.log(this.form.value);
  }
}

Submitted data form की current structure के according होता है।

Performance Considerations

Dynamic forms heavy हो सकते हैं।

Best practices:

  • Unnecessary controls add न करें
  • Large FormArray में trackBy use करें
  • valueChanges subscriptions clean up करें
  • Form structure reuse करें जहाँ possible हो

Common Mistakes

  • Template-driven forms से dynamic behavior try करना
  • Validators update करने के बाद updateValueAndValidity() call न करना
  • Controls remove करके UI sync न करना
  • Complex logic template में डाल देना

कब Dynamic Forms Use करें

Dynamic forms best suited हैं:

  • CMS systems
  • Admin panels
  • Survey forms
  • Role-based forms
  • Configurable workflows

Angular Dynamic Forms Angular Reactive Forms की advanced capability हैं। इस chapter के बाद आप किसी भी runtime-based form requirement को confidently handle कर सकते हैं। अगले chapter में हम Angular Forms Advanced concepts cover करेंगे, जहाँ performance, optimization और complex patterns discuss होंगे।