我调用一个API,该API返回这样的数据
[
{
"id": 9,
"name": "Past Menu",
"serveDate": "2019-05-08 00:00:00",
"meals": [
{
"id": 27,
"name": "6",
"description": "6",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 6,
"status": "ENABLED"
},
{
"id": 28,
"name": "7",
"description": "7",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 7,
"status": "ENABLED"
},
{
"id": 30,
"name": "9",
"description": "9",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 9,
"status": "ENABLED"
}
]
},
{
"id": 8,
"name": "Bomb Menu",
"serveDate": "2019-05-10 00:00:00",
"meals": [
{
"id": 28,
"name": "7",
"description": "7",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 7,
"status": "ENABLED"
},
{
"id": 30,
"name": "9",
"description": "9",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 9,
"status": "ENABLED"
},
{
"id": 31,
"name": "10",
"description": "10",
"image": "",
"mealType": "BREAKFAST",
"unitPrice": 10,
"status": "ENABLED"
}
]
}
]
每个父对象还具有一个子对象(meals)
,用户可以选择删除任何子对象(meals)
,并且在调用该操作时,它也应该能够获取父ID。 。一个例子是,当选择ID为27
的餐对象被删除时,我应该能够得到父id
,即9
HTML
<div *ngFor="let item of menuList">
<h2>Menu</h2>
{{item.name}} - {{item.servedate}}
<h2>Meals</h2>
<div *ngFor="let item of item.meals">
<span (click)="removeMeal(item)">{{item.name}} - {{item.mealType}}</span>
</div>
</div>
JS
removeMeal(item) {
alert(item.id)
for (let s = 0; s < this.menuList.length; s++) {
if (this.menuList[s].meals.length > 0) { // Iterate only if the array is not empty
for (let r = 0; r < this.menuList[s].meals.length; r++) {
if (this.menuList[s].meals[r].id === item.id) {
this.menuList[s].meals.splice(r, 1);
}
}
}
}
}
代码中的id
是提醒我用餐的ID,但我想获得父项id
答案 0 :(得分:1)
通过重命名*ngFor
语句的变量来尝试以下操作,以弄清哪些是顶级项目与item.meals
的进餐。然后更新removeMeal()
以获取父ID值,同时将item.id
作为removeMeal()
处理程序传递到(click)
中:
模板:
<div *ngFor="let item of menuList">
<h2>Menu</h2>
{{item.name}} - {{item.servedate}}
<h2>Meals</h2>
<div *ngFor="let meal of item.meals">
<span (click)="removeMeal(meal, item.id)">{{meal.name}} - {{meal.mealType}}</span>
</div>
</div>
组件:
removeMeal(item, parentId) {
alert(parentId);
// ...
}
希望有帮助!