Reputation: 910
I am creating an editable table from the data that I am getting from the back end now I want to save the data that has been updated. I have tried using formControl but it only save the data that is in the last column Here is my code
<form [formGroup]="pagesForm">
<tr *ngFor="let data of pagesArray; let i = index; trackBy: trackByFn">
<td style="text-align: center;" >
<input type="text" formControlName="nameControl" value=[data.name]>
</td>
<td style="text-align: center;">
<input type="text" formControlName="descriptionControl"
vaue=[data.description]>
</td>
</tr>
<button class="btn btn-common" (click)="submit(pagesForm)">Save</button>
</form>
Can anyone help me to save this table data in bulk
Upvotes: 3
Views: 2736
Reputation: 73357
In case of reactive form, which I suggest, especially when dealing with an array... with that you need a FormArray
to which you push your values when you get them from the backend.
So you can build your form:
constructor(private fb: FormBuilder) {
this.pagesForm = this.fb.group({
arr: this.fb.array([])
})
}
and when you receive your data, in the callback (subscribe
or then
if you are using promises) call a method, in this example setFormArray()
that populates your form array:
setFormArray() {
let arr = this.pagesForm.controls.arr;
this.pagesArray.forEach(x => {
arr.push(this.fb.group({
name: x.name,
description: x.description
}))
})
}
Then you can modify your template to iterate the formarray:
<form [formGroup]="pagesForm" (ngSubmit)="submit(pagesForm.value)">
<div formArrayName="arr">
<tr *ngFor="let page of pagesForm.controls.arr.controls; let i = index"
[formGroupName]="i" >
<td>
<input type="text" formControlName="name">
</td>
<td>
<input type="text" formControlName="description">
</td>
</tr>
</div>
<button type="submit">Save</button>
</form>
Now you end up with an form object that contains property arr
, which is an array of your data.
Here's a demo: http://plnkr.co/edit/zfpbUzkvMLOn8CCermGD?p=preview
Hope this helps! :)
Upvotes: 1