为了账号安全,请及时绑定邮箱和手机立即绑定

在角度的html上条件打印

在角度的html上条件打印

拉莫斯之舞 2022-01-20 20:29:50
我正在遍历产品列表,然后检查产品 ID 是否已经存在于 products(objects) 数组中,然后如果产品不在对象中,则打印数量,然后尝试打印 0。下面是代码我一直尝试到现在。<ion-item class="added" *ngFor="let item of fetchProducts();let key=index;">  <ng-container  *ngFor="let cartitem of cart" >     <span class="count" *ngIf="cartitem.p_id==item.p_id;">         {{cartitem.qty}}     </span>   </ng-container></ion-item>item如果不在cartitem同一跨度中,如何打印 0 。
查看完整描述

3 回答

?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

您可以使用如下所示的三元运算符简单地执行此操作。


<ng-container  *ngFor="let cartitem of cart" >

     <span class="count">

      {{cartitem.p_id==item.p_id ? cartitem.qty : 0 }}

     </span>

</ng-container>


查看完整回答
反对 回复 2022-01-20
?
慕森卡

TA贡献1806条经验 获得超8个赞

可以在 for 循环中使用 *ngIf else 条件 -


<ion-item class="added" *ngFor="let item of fetchProducts();let key=index;">

  <ng-container *ngFor="let cartitem of cart">

    <span class="count" *ngIf="cartitem.p_id==item.p_id; then content else other_content">

    </span>

    <ng-template #content>{{cartitem.qty}}</ng-template>

    <ng-template #other_content>0</ng-template>


  </ng-container>

</ion-item>


查看完整回答
反对 回复 2022-01-20
?
白衣非少年

TA贡献1155条经验 获得超0个赞

我不使用模板逻辑,而是将逻辑移到类中。


cart并且products显然在课堂上可用。因此调整类中的函数以根据需要返回产品列表(带有数量信息)并在模板中fetchProducts使用单个循环。ngFor


或者添加一个新功能getProductsWithQuantity...


在你的课上


    public getProductsWithQuantity() {

        return this.fetchProducts().map(product => {

            ...product,

            quantity: this.getQuantity(product);

        });

    }


    private getQuantity(product) {

        const foundCartItem = this.cart.find(cartItem => product.id === cartItem.id);

        if (foundCartItem) {

            return foundCartItem.qty;

        }

        return 0;

    }

在您的模板中:


<ion-item class="added" *ngFor="let item of getProductsWithQuantity();let key=index;">

   <span class="count">

       {{item.qty}}

   </span>

...


查看完整回答
反对 回复 2022-01-20
  • 3 回答
  • 0 关注
  • 152 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号