I have to create a dynamic form where label and input fields will both are text-field(user will fill at run time). And user can add as many as fields he requires. I have requirements where I have to generate. property file in backend. Where key-value pair is required and the user decides how much key-value pair he needs.
1 Answer
Create FormGroup as
keyValueFA = new FormArray([this.newKeyValueFG]);
propertyFG = new FormGroup({
keyValue: this.keyValueFA,
});
getter to create new FormGroup
get newKeyValueFG(): FormGroup {
return new FormGroup({
key: new FormControl(null),
value: new FormControl(null),
});
}
Other methods to set, remove, get FormGroup
get keyValueArrayFGControls(): FormGroup[] {
return this.keyValueFA.controls as FormGroup[];
}
addNewKeyValueFG(): void {
this.keyValueFA.push(this.newKeyValueFG);
}
removeNewKeyValueFG(index: number): void {
this.keyValueFA.removeAt(index);
}
In template iterate keyValueArrayFGControls
<form [formGroup]="propertyFG">
<div
formArrayName="keyValue"
*ngFor="let fg of keyValueArrayFGControls; let i = index"
>
<div [formGroup]="fg">
{{ i + 1 }})
<div><input type="text" formControlName="key" placeholder="Key" /></div>
<div>
<input type="text" formControlName="value" placeholder="Value" />
</div>
<button (click)="removeNewKeyValueFG(i)">Remove</button>
</div>
</div>
<button (click)="addNewKeyValueFG()">Add</button>
</form>

FormArrayofFormGroup. You should share your code.