Reactive Forms in Real Applications: dynamic form generation using FormArray; custom validators and asynchronous validation; centralized error handling; submitting forms to APIs and form state management

Angular reactive forms एक form को आपके TypeScript में data की तरह model करते हैं: FormControl और FormGroup fields hold करते हैं, FormArray इनकी एक growing list handle करता है, validators (custom और async सहित) input check करते हैं, और आप API को value submit करते हैं।

12 min read · 8 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Forms जिस Data को आप Control करते हैं

FestConnect का registration form सिर्फ़ input boxes से ज़्यादा है: इसे names और emails validate करना है, एक team को members की एक variable number add करने देना है, सब कुछ valid होने तक submission block करना है, और फिर data backend को भेजना है। Angular के reactive forms इस सब को form को आपके TypeScript code में data की तरह model करके handle करते हैं, जिसे आप programmatically inspect, validate, और change कर सकते हैं।

यह lesson reactive-forms building blocks cover करता है, FormControl, FormGroup, FormArray, और validators, plus errors कैसे handle करें और एक API को submit कैसे करें। यह वह front-end skill है जिसे आप हर real form पर इस्तेमाल करेंगे।

Theory

FormControl, FormGroup, FormArray

तीन classes एक reactive form build करती हैं।

एक FormControl एक single field represent करता है (name box), इसकी value और validation state hold करते हुए। एक FormGroup कई controls को एक form में bundle करता है (name, email, phone)। एक FormArray controls की एक dynamic list है, perfect जब fields की number fixed नहीं है, एक team registration जैसा जहाँ members runtime पर add या remove हो सकते हैं।

चूँकि form आपकी class में इन objects की तरह रहता है, आप इसकी value पढ़ सकते हैं, validity check कर सकते हैं, एक FormArray entry add कर सकते हैं, या इसे reset कर सकते हैं, सब code में, यही वजह है reactive forms real applications के लिए powerful हैं।

Practical

एक FormArray वाला एक Reactive Form

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

form = new FormGroup({
  name:  new FormControl('', [Validators.required]),
  email: new FormControl('', [Validators.required, Validators.email]),
  members: new FormArray([]),        // a dynamic, growing list of controls
});

addMember() {
  this.form.controls.members.push(new FormControl('', Validators.required));
}
// members starts empty; addMember() appends a new required field at runtime.

Theory

Validators, Errors, और Submitting

Validators decide करते हैं input acceptable है या नहीं। Built-in ones में Validators.required और Validators.email शामिल हैं। एक custom validator एक function है जो आप लिखते हैं जो एक error object return करता है (या null अगर valid है), 'must be a college email' जैसे rules के लिए। एक async validator एक Observable या Promise return करता है, इस्तेमाल होता है जब validation को server चाहिए, जैसे check करना एक username पहले से लिया नहीं गया है।

Error handling के लिए, आप एक control की errors, invalid, और touched state पढ़ते हैं messages सिर्फ़ user के interact करने के बाद दिखाने के लिए। Submit पर, आप form.valid check करते हैं, फिर Angular के HttpClient से form.value अपने API को भेजते हैं। Form में validate कीजिए, सिर्फ़ valid होने पर submit कीजिए।

Practical

Valid होने पर Form को एक API को Submit करना

constructor(private http: HttpClient) {}

submit() {
  if (this.form.invalid) {
    this.form.markAllAsTouched();     // reveal validation errors
    return;
  }
  // form.value is a plain object ready to send
  this.http.post('/api/register', this.form.value)
    .subscribe(() => console.log('Registered!'));
}
// A custom validator example (returns an error object or null):
// const collegeEmail = (c: AbstractControl) =>
//   c.value?.endsWith('@college.edu') ? null : { collegeEmail: true };

Quiz

एक reactive form में, कौन सी class आपको fields की एक dynamic list build करने देती है जिसमें user runtime पर add या remove कर सकता है (जैसे team members add करना)?

  1. FormControl, क्योंकि यह एक single field है
  2. FormArray, controls की एक dynamic list जिसमें आप runtime पर add या remove कर सकते हैं
  3. FormGroup, क्योंकि यह fixed fields group करता है
  4. Validators, क्योंकि ये count control करते हैं
Show the answer

FormArray, controls की एक dynamic list जिसमें आप runtime पर add या remove कर सकते हैं

FormArray controls की एक dynamic list represent करता है जिसमें आप runtime पर push या remove कर सकते हैं, exactly वह जो team members की एक variable number को चाहिए। Option A, FormControl, एक single field है, list नहीं। Option C, FormGroup, named controls (name, email, phone) का एक FIXED set एक form में bundle करता है; यह एक growing/shrinking list के लिए designed नहीं है। Option D, Validators, check करता है input valid है या नहीं; इसका fields की number से कोई लेना-देना नहीं है। एक field के लिए FormControl, एक fixed set के लिए FormGroup, और एक dynamic list के लिए FormArray इस्तेमाल कीजिए।

Think first

Real Apps के लिए Template-Driven Forms से Reactive Forms को क्यों Prefer किया जाता है?

Angular में HTML में defined template-driven forms भी हैं। Larger apps reactive forms क्यों favour करते हैं? फिर tap कीजिए।

Show the answer

क्योंकि reactive forms form का structure और logic आपके TYPESCRIPT code में डालते हैं, जो इन्हें real apps को चाहिए complex forms के लिए ज़्यादा explicit, testable, और powerful बनाता है। एक template-driven form में, form HTML template में directives से implicitly build होता है, जो एक tiny form के लिए quick है पर complexity बढ़ने के साथ manage करना hard बन जाता है: dynamic fields, cross-field rules, और custom validation markup में express करना awkward है, और पूरे form का shape देखने के लिए कोई single जगह नहीं है। Reactive forms इसे flip करते हैं: आप component class में FormControl, FormGroup, और FormArray define करते हैं, तो पूरा form एक data structure है जिसे आप directly पढ़ सकते हैं, manipulate कर सकते हैं, और reason कर सकते हैं, code की एक line से एक field add कीजिए (FormArray.push), एक custom या async validator को एक plain function की तरह attach कीजिए, validity और errors programmatically check कीजिए, और values को at will reset या patch कीजिए। यह explicitness इन्हें UNIT TEST करना भी कहीं ज़्यादा easy बनाता है, क्योंकि आप एक template render किए बिना code में form create और drive कर सकते हैं। और यह scale करता है: same patterns एक two-field login और एक fifty-field multi-step wizard दोनों handle करते हैं। Template-driven forms की बहुत simple cases के लिए अभी भी अपनी जगह है, पर FestConnect जैसे एक app में dynamic, validated, API-submitting forms के लिए, reactive forms का control और testability जीतता है। कुछ भी non-trivial के लिए code में form as data, markup में form से बेहतर है।

Summary

Key takeaways

  • Reactive forms एक form को component class में data की तरह model करते हैं, तो आप इसे code में inspect, validate, और change कर सकते हैं।
  • FormControl एक field है; FormGroup controls का एक fixed set bundle करता है; FormArray एक dynamic list है जिसमें आप add या remove कर सकते हैं।
  • Validators input check करते हैं: built-in (Validators.required, Validators.email), custom (एक error या null return करने वाला function), और async (एक Observable/Promise return करता है, जैसे server checks)।
  • एक control की errors/invalid/touched state के through errors handle कीजिए, interaction के बाद messages दिखाते हुए।
  • Submit पर, form.valid check कीजिए, फिर HttpClient से एक API को form.value भेजिए।
  • Reactive forms real apps को suit करते हैं क्योंकि ये explicit, testable हैं, और dynamic और custom validation अच्छी तरह handle करते हैं।
  • Memory hook: structure के लिए FormControl/Group/Array, rules के लिए validators, API को form.value।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Fundamentals of Angular (v17) for Single Page Applications

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Reactive Forms in Real Applications: dynamic form generation using FormArray; custom validators and asynchronous validation; centralized error handling; submitting forms to APIs and form state management · Fundamentals of Full Stack Web Development (Major-15-01) · Gri-Learn