问题
I have a service which returns a JSON of type array[obj1{name, usage, id}, obj2{name, usage, id}] on HTML page I am creating a form with form field = name and it is pre-populated with value = usage. Ex: if there are 2 objects inside array where name1=a usage1=1 and name2=b and usage2=2, 2 form fields will be created. Form field names will be name1 and name2 and will be filled already with usage1 and usage2 value respectively. I am doing this with this code:
<form>
<div class="form-row">
<div class="form-group" *ngFor="let item of items">
<label>{{item.name}}</label>
<input type="number" min="0" [id]="item.name" [name]="item.name" class="form-control" [(ngModel)]="item.usage">
</div>
</div>
</form>
It is working fine. Now suppose user changes the value for usage1 and usage2. On submit button I have to create a json object in typescript and send it in the API. I am facing issues to create the JSON object. I have tried:
onSubmit{
this.changedValues = this.items.usage;
console.log(this.changedValues);
}
But console.log return undefined. Json object I am expecting should be something of they type:
changedValues[{upadatedUsage1, id1},{updatedUsage2, id2}]
How can I create a json object dynamically and also how can I send the correct id with the correct updated usage value. Thank you
回答1:
The reason for undefined value is that, items is an array and hence doesn't have the property usage
onSubmit {
this.changedValues = this.items;
console.log(this.changedValues);
}
This should give the array with updated values.
来源:https://stackoverflow.com/questions/62771703/create-json-object-from-dynamic-ngmodel