首页 > 解决方案 > Angular - 模板驱动形式 - 以数组中对象的形式发送数组数据

问题描述

我在多选下拉列表中显示了一些列表。提交的数据在表单中

[ "object1" , "object2" ]

我希望它以以下形式提交:

[ { object 1 } , { object 2} ]

我的 html 下拉列表代码:

<select name="service" multiple matNativeControl required ngModel>
  <option *ngFor="let service of subCategoriesList" value="{{service.id}}">{{service.service}}</option>
</select>

组件.ts 文件:

addPackage(form: NgForm){
    const body = {
      package_name : form.value.name,
      services: form.value.service, //the value required in objects in an array   
    }
    console.log("add package body is: ", body)

任何帮助将不胜感激。

标签: arraysangularformsangular2-template

解决方案


尝试使用Object.assign

在 addPackage 函数中:然后为每个选择调用创建一个空数组Object.assign

addPackage(form: NgForm){
    let selections=[];
    form.value.service.forEach(element => {
      var selection= Object.assign({}, { element });
      selections.push(selection);
    });
    const body = {
      package_name : form.value.name,
      services: selections, //put your created objects here   
    }
    console.log("add package body is: ", body)
}

推荐阅读