从Angular中获取Array中的所有材质

时间:2017-11-08 03:34:27

标签: angular angular-reactive-forms angular4-forms

我在stackblitz中有这个代码需要获取所有材料。我怎样才能获得所有材料而不仅仅是一种材料。输出只是一种材料,而不是列表?这是我下面的代码 https://stackblitz.com/edit/angular-qssycg?file=app/app.component.ts

  

JSON

orders =
  [
  {
    "id": 1,
    "name": "Not Available",
    "address": "Not Available",
    "city": "Not Available",
    "contact_number": "Not Available",
    "created_at": "2017-10-26 16:12:22",
    "updated_at": "2017-10-26 16:12:22",
    "materials": [
      {
        "id": 21,
        "sku": "D22D12D4",
        "name": "D-2, 2D-1, 2D-4",
        "created_at": "2017-10-26 03:03:43",
        "updated_at": "2017-10-26 03:03:43",
        "pivot": {
          "supplier_id": 1,
          "material_id": 21
        }
      },
      {
        "id": 40,
        "sku": "ACWNAIL",
        "name": "Assorted C.W. Nails",
        "created_at": "2017-10-26 03:19:54",
        "updated_at": "2017-10-26 03:23:21",
        "pivot": {
          "supplier_id": 1,
          "material_id": 40
        }
      },
      {
        "id": 49,
        "sku": "DDJENAMEL",
        "name": "Doors & Door Jambs - Enamel",
        "created_at": "2017-10-26 03:33:06",
        "updated_at": "2017-10-26 03:33:06",
        "pivot": {
          "supplier_id": 1,
          "material_id": 49
        }
      }
    ]
  }
]
  

TS

patchValues() {
    let rows = this.myForm.get('rows') as FormArray;
    this.orders.forEach(material => {
      rows.push(this.fb.group({material_id: material.materials[0].id,material_name: material.materials[0].name, quantity: material.materials[0]}))
    })
  }

1 个答案:

答案 0 :(得分:0)

如评论中所述,您需要迭代到嵌套数组并将这些值推送到表单数组。所以你的patchValues() { let rows = this.myForm.get('rows') as FormArray; this.orders.forEach(material => { material.materials.forEach(x => { rows.push(this.fb.group({material_id: x.id, material_name: x.name, quantity: 'there is no quantity in your data'})) }) }) } 应该是这样的:

quantity

请注意,您的JSON中似乎没有orders。此解决方案也只考虑到{{1}}数组中只有一个对象。如果您知道还有更多,则还需要在formarray中创建表单组。

<强> DEMO