Reputation: 11
I get the Object essensplan
const essensplan = [
{ id: 1, essenProWoche: [11, 14, 17, 20, 12] },
...
{ id: 8, essenProWoche: [15, 14, 13, 12, 11] }
];
from an emulated server and I want the possibility for the user to change each value of the array essenProWoche and give it back to the server.
I tried
<div>
<label>Änderungen:
<input [(ngModel)]="essensplan.essenProWoche" placeholder="Name">
</label>
</div>
which doesn't work because it's not returned as an array
and
<label *ngFor="let id of essensplan.essenProWoche; let i = index">
<input type="number" [(ngModel)]="essensplan.essenProWoche[i]">
</label>
which changes the values live in the browser, but they are not saved.
I save the inputs by the following functions:
essensplan-detail.component.ts
save(): void {
this.essensplanService.updateEssensplan(this.essensplan)
.subscribe(() => this.goBack());
}
essensplan.service.ts
updateEssensplan(essensplan: Essensplan): Observable<any> {
return this.http.put(this.speisekarteUrl, essensplan, httpOptions).pipe(
tap(_ => this.log(`updated essensplan id=${essensplan.id}`)),
catchError(this.handleError<any>('updateEssensplan'))
Upvotes: 0
Views: 1198
Reputation: 2455
Do you want two-way binding functionality?
If you change value inside model than automatically update your json too.
In Your html :
<div *ngFor="let items of essensplan">
<div *ngFor="let opt of items.essenProWoche; index as i; trackBy: trackByFn">
<input type="number" [(ngModel)]="items.essenProWoche[i]">
</div>
</div>
In Your Ts :
trackByFn(index, item) {
return index;
}
For Live demo check this Stackblitz
Upvotes: 0
Reputation: 3334
Another way, you can make the array elements as a string. When you get an array of few objects from server:
this.essensplan = [
{ id: 1, essenProWoche: [11, 14, 17, 20, 12] },
{ id: 2, essenProWoche: [11, 14, 17, 20, 12] }
];
Then you can change it as:
this.essensplan.map(item => {
item.essenProWoche = item.essenProWoche.join(',');
});
And you can use:
<ng-template ngFor let-item [ngForOf]="essensplan">
<input type="text" [(ngModel)]="item.essenProWoche">
</ngtemplate>
<!-- but make sure to enter the values with commas -->
And when you are about to save it:
save(): void {
this.essensplan.map(item => {
item.essenProWoche = item.essenProWoche.split(','); // because it was a string
});
this.essensplanService.updateEssensplan(this.essensplan)
.subscribe(() => this.goBack());
}
Upvotes: 1
Reputation: 5301
Are you trying to call the save function automatically on change of each value? If yes, then use a formControl
and subscribe to the valueChanges
event. you can call your save
function everytime the value changes.
Upvotes: 0