Forms
Reactive Forms
FormGroup, FormControl
💡 Reactive forms ek engineer ka blueprint jaisa hai — poora form structure CODE (TypeScript) mein EXPLICITLY define karte ho, PEHLE se — template sirf us structure ko "display" karta hai. Zyada verbose, lekin zyada CONTROL, TESTABLE, PREDICTABLE.
Reactive forms COMPONENT CLASS mein form structure define karte hain — FormControl (single field), FormGroup (multiple fields grouped). ReactiveFormsModule import karna zaroori hai. Complex, dynamic, aur highly-testable forms ke liye INDUSTRY STANDARD approach hai.
import { FormGroup, FormControl, Validators } from '@angular/forms';
export class SignupComponent {
signupForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required, Validators.minLength(8)])
});
onSubmit() {
if (this.signupForm.valid) {
console.log(this.signupForm.value); // { email: '...', password: '...' }
}
}
}
// Template:
// <form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
// <input formControlName="email">
// <input formControlName="password" type="password">
// <button [disabled]="signupForm.invalid">Sign Up</button>
// </form>⚛️
Reactive forms ek engineer ka blueprint jaisa hai — poora form structure CODE (TypeScript) mein EXPLICITLY define karte ho, PEHLE se — template sirf us structure ko "display" karta hai. Zyada verbose, lekin zyada CONTROL, TESTABLE, PREDICTABLE.
1 / 2
⚡ Quick Recap
- FormGroup/FormControl = form structure CODE mein explicitly defined
- ReactiveFormsModule import zaroori hai
- Complex forms, testability ke liye industry-standard approach
On this page (2 subtopics)
FormBuilder service naya FormGroup/FormControl banaने ka SHORTHAND deता hai — fb.group({...}) verbose "new FormGroup({ new FormControl(...) })" syntax se bahut CLEANER hai.
import { FormBuilder } from '@angular/forms';
export class SignupComponent {
constructor(private fb: FormBuilder) { }
signupForm = this.fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required]
});
// fb.group() automatically FormControls banata hai array syntax se:
// [initialValue, validators]
}Tip: FormBuilder almost UNIVERSALLY use hota hai production Angular code mein — raw "new FormGroup()" syntax rarely dikhta hai, FormBuilder ki concise syntax standard hai.
FormControl/FormGroup ka valueChanges ek OBSERVABLE hai — jab bhi value CHANGE ho, notify karta hai. Real-time search, conditional field showing/hiding jaisi features ke liye common.
this.signupForm.get('email')?.valueChanges.subscribe(value => {
console.log('Email changed to: ' + value);
});
// Real-time search example:
// this.searchControl.valueChanges.subscribe(query => {
// this.performSearch(query);
// });Tip: valueChanges Observable RxJS operators (debounceTime, distinctUntilChanged) ke saath COMBINE hota hai bahut common pattern mein — search-as-you-type ke liye, RxJS category mein detail se aayega.