首页 > 解决方案 > for循环中的离子4多阵列

问题描述

我需要*ngFor在ionic4中使用一个。

这是我的代码,

        <ion-item *ngFor="let item of data.name">
            <ion-checkbox mode="md"  [(ngModel)]="data.checked" value="0" ></ion-checkbox>
            <ion-label class="title-add">{{item}} </ion-label>
            <ion-label slot="end" class="ion-text-end price-add">
                <ion-text color="medium">+ {{prop}} ريال </ion-text>
            </ion-label>
        </ion-item>

我有两个数组

data.namedata.price

我需要在 ion-item 中创建相同的循环。我怎样才能做到?

API 响应:

male_addition: [
{
id: 33,
name: [
"pepsi",
"cola"
],
name_additions: "drinks",
price: [
"3",
"3"
],
type: 2,
male_id: 15,
details_id: 45,
created_at: "2020-02-28 16:16:18",
updated_at: "2020-02-28 16:16:18"
}
]

标签: angularionic4

解决方案


您应该将两个数组映射到一个新的类型为 的对象数组中,假设它们总是相互关联{name: string; price: number;}

做这样的事情,

this.namePriceArray = this.male_addition.flatMap(data => 
                                    data.name.map((n, i) => ({name: n, price: data.price[i]})));

然后你就可以this.namePriceArray在你的*ngFor里面使用了<ion-item>

        <ion-item *ngFor="let item of namePriceArray">
            <ion-checkbox mode="md"  [(ngModel)]="data.checked" value="0" ></ion-checkbox>
            <ion-label class="title-add">{{item.name}} {{item.price}}</ion-label>
            <ion-label slot="end" class="ion-text-end price-add">
                <ion-text color="medium">+ {{prop}} ريال </ion-text>
            </ion-label>
        </ion-item>

推荐阅读