从Dynamic NgModel创建JSON对象 [英] Create JSON object from Dynamic NgModel

查看:57
本文介绍了从Dynamic NgModel创建JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务,该服务在HTML页面上返回类型为array[obj1{name, usage, id}, obj2{name, usage, id}]的JSON.我正在使用表单字段=名称创建一个表单,并预先填充了值=用法.例如:如果数组内有2个对象,其中name1 = a用法1 = 1和name2 = b和用法2 = 2,则将创建2个表单字段.表单字段名称将为name1和name2,并且将分别已经分别填充了用法1和用法2的值.我正在使用以下代码进行此操作:

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>

工作正常.现在,假设用户更改了用法1和用法2的值.在提交按钮上,我必须在typescript中创建一个json对象,并将其发送到API.我在创建JSON对象时遇到问题.我已经尝试过:

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);
}

但是console.log返回未定义.我期望的Json对象应该是他们键入的东西:

But console.log return undefined. Json object I am expecting should be something of they type:

changedValues[{upadatedUsage1, id1},{updatedUsage2, id2}]

如何动态创建json对象,以及如何发送具有正确的更新用法值的正确ID.谢谢

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

推荐答案

未定义值的原因是 items 是一个数组,因此没有属性 usage

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.

这篇关于从Dynamic NgModel创建JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆