问题描述
我在stackblitz中有此代码,需要获取所有材料.我如何才能获得所有材料而不仅仅是一个.输出仅是一种材料,而不是列表?这是我的下面的代码 https://stackblitz.com/edit/angular-qssycg?file = app/app.component.ts
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 belowhttps://stackblitz.com/edit/angular-qssycg?file=app/app.component.ts
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
}
}
]
}
]
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]}))
})
}
推荐答案
如注释中所述,您需要迭代到嵌套数组并将这些值推送到表单数组.因此,您的 patchValues
应该如下所示:
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'}))
})
})
}
请注意,您的JSON中似乎没有 quantity
.同样,此解决方案仅考虑到 orders
数组中只有一个对象.如果您知道还有更多内容,则还需要在formarray中创建表单组.
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
这篇关于从Angular数组中获取所有材质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!