Get All Materials from Array in Angular

2019-07-30 19:09发布

I have this code in stackblitz that needs to get all materials. How can i get all the materials and not just one. The output is just one materials and not the lists? Here's my code below 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条回答
祖国的老花朵
2楼-- · 2019-07-30 19:47

As mentioned in comments, you need to iterate to nested array and push those values to your form array. So your patchValues should look like this:

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

notice, that you don't seem to have quantity in your JSON. Also this solution only takes in consideration that you have only one object in your orders array. If you are aware that there is more, you need to also create formgroups in your formarray.

DEMO

查看更多
登录 后发表回答