Get All Materials from Array in Angular

帅比萌擦擦* 提交于 2019-12-11 12:13:48

问题


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:


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



来源:https://stackoverflow.com/questions/47171155/get-all-materials-from-array-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!