Javascript 从具有角度的子对象传递项时获取父ID
我调用了一个API,它返回如下数据Javascript 从具有角度的子对象传递项时获取父ID,javascript,angular,Javascript,Angular,我调用了一个API,它返回如下数据 [ { "id": 9, "name": "Past Menu", "serveDate": "2019-05-08 00:00:00", "meals": [ { "id": 27, "name": "6", "description": "6", "image": "", "mealType": "BREAKFAST",
[
{
"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"
}
]
}
]
每个父对象也有一个子对象,用户可以选择删除任何子对象,并且在调用该操作时,还应该能够获取父对象id。例如,当选择删除id为27的用餐对象时,我应该能够获得父id,即9
HTML
JS
代码的id是我在警报中得到的,是餐食的id,但我想得到父id,而不是尝试以下操作,重命名*ngFor语句的变量,以明确哪些是顶级项目,哪些是item.fends的餐食。然后更新RemoveDine以接受父id值,同时将item.id作为单击处理程序传入RemoveDine: 模板:
<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) {
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);
}
}
}
}
}
<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);
// ...
}