Forms
Dynamic Forms
FormArray, Runtime Fields
💡 FormArray ek expandable form jaisa hai — jaise ek job application jisme "add another skill" button ho, jitni chaho utni fields add kar sako, RUNTIME par — fixed number of fields nahi, dynamically grow/shrink hoti hain.
FormArray dynamic, VARIABLE-LENGTH lists of form controls manage karta hai — jab tumhe pata nahi kितने fields honge (jaise "add multiple phone numbers"). push()/removeAt() se runtime par controls add/remove karte hain.
import { FormGroup, FormArray, FormControl } from '@angular/forms';
export class SkillsFormComponent {
form = new FormGroup({
skills: new FormArray([
new FormControl('') // shuru mein ek field
])
});
get skills() {
return this.form.get('skills') as FormArray;
}
addSkill() {
this.skills.push(new FormControl(''));
}
removeSkill(index: number) {
this.skills.removeAt(index);
}
}
// Template:
// <div formArrayName="skills">
// <div *ngFor="let skill of skills.controls; let i = index">
// <input [formControlName]="i">
// <button (click)="removeSkill(i)">Remove</button>
// </div>
// </div>
// <button (click)="addSkill()">Add Skill</button>🔧
FormArray ek expandable form jaisa hai — jaise ek job application jisme "add another skill" button ho, jitni chaho utni fields add kar sako, RUNTIME par — fixed number of fields nahi, dynamically grow/shrink hoti hain.
1 / 6
⚡ Quick Recap
- FormArray = variable-length list of controls
- push()/removeAt() = runtime par fields add/remove
- "Add another item" jaisi UI patterns ke liye perfect
On this page (2 subtopics)
FormArray sirf simple controls ki list nahi — FormGroups ki bhi list ho sakती hai, jaise "multiple addresses, har ek mein multiple fields (street, city)".
addresses = new FormArray([
new FormGroup({
street: new FormControl(''),
city: new FormControl('')
})
]);
addAddress() {
this.addresses.push(new FormGroup({
street: new FormControl(''),
city: new FormControl('')
}));
}Tip: Complex nested forms (jaise "invoice with multiple line items, har item ke multiple fields") is pattern ka natural extension hain — FormArray ke andar FormGroups, jitni depth chahiye.
Bade applications mein forms kabhi-kabhi SERVER se aane wale CONFIGURATION (JSON schema) se DYNAMICALLY generate hote hain — ek generic "form builder" component jo kisi bhi schema se form render kar sake.
// Simplified concept:
const formSchema = [
{ name: 'email', type: 'email', required: true },
{ name: 'age', type: 'number', required: false }
];
// Component loop karके FormGroup dynamically banाता hai schema se,
// aur ek generic template *ngFor se fields render karta haiTip: Ye advanced pattern hai — usually LARGE enterprise applications mein use hota hai jaha forms bahut VARIED aur configuration-driven hote hain (jaise ek CMS jaha admin naye form fields add kar sakta hai bina code deploy kiye).