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

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

问题描述

我有一个服务,它在 HTML 页面上返回 array[obj1{name, usage, id}, obj2{name, usage, id}] 类型的 JSON 我正在创建一个带有表单的表单field = name 并且它预先填充了 value = usage.例如:如果数组中有 2 个对象,其中 name1=a usage1=1 and name2=b and usage2=2,将创建 2 个表单字段.表单字段名称将是 name1 和 name2,并且将分别用 usage1 和 usage2 值填充.我正在使用此代码执行此操作:

<div class="form-row"><div class="form-group";*ngFor=让项目中的项目"><label>{{item.name}}</label><输入类型=数字"min=0"[id]=item.name"[名称]=item.name"类=表单控制"[(ngModel)]=item.usage">

</表单>

它工作正常.现在假设用户更改了usage1 和usage2 的值.在提交按钮上,我必须在打字稿中创建一个 json 对象并将其发送到 API 中.我在创建 JSON 对象时遇到了问题.我试过了:

onSubmit{this.changedValues = this.items.usage;控制台日志(this.changedValues);}

但是 console.log 返回 undefined.我期待的 Json 对象应该是他们类型的东西:

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

如何动态创建 json 对象,以及如何使用正确的更新使用值发送正确的 id.谢谢

解决方案

undefined value 的原因是,items 是一个数组,因此没有属性 usage

onSubmit {this.changedValues = this.items;控制台日志(this.changedValues);}

这应该为数组提供更新的值.

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

解决方案

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.

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆