猿问

在角度的html上条件打印

我正在遍历产品列表,然后检查产品 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 。


拉莫斯之舞
浏览 153回答 3
3回答

一只萌萌小番薯

您可以使用如下所示的三元运算符简单地执行此操作。<ng-container&nbsp; *ngFor="let cartitem of cart" >&nbsp; &nbsp; &nbsp;<span class="count">&nbsp; &nbsp; &nbsp; {{cartitem.p_id==item.p_id ? cartitem.qty : 0 }}&nbsp; &nbsp; &nbsp;</span></ng-container>

慕森卡

可以在 for 循环中使用 *ngIf else 条件 -<ion-item class="added" *ngFor="let item of fetchProducts();let key=index;">&nbsp; <ng-container *ngFor="let cartitem of cart">&nbsp; &nbsp; <span class="count" *ngIf="cartitem.p_id==item.p_id; then content else other_content">&nbsp; &nbsp; </span>&nbsp; &nbsp; <ng-template #content>{{cartitem.qty}}</ng-template>&nbsp; &nbsp; <ng-template #other_content>0</ng-template>&nbsp; </ng-container></ion-item>

白衣非少年

我不使用模板逻辑,而是将逻辑移到类中。cart并且products显然在课堂上可用。因此调整类中的函数以根据需要返回产品列表(带有数量信息)并在模板中fetchProducts使用单个循环。ngFor或者添加一个新功能getProductsWithQuantity...在你的课上&nbsp; &nbsp; public getProductsWithQuantity() {&nbsp; &nbsp; &nbsp; &nbsp; return this.fetchProducts().map(product => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...product,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; quantity: this.getQuantity(product);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; private getQuantity(product) {&nbsp; &nbsp; &nbsp; &nbsp; const foundCartItem = this.cart.find(cartItem => product.id === cartItem.id);&nbsp; &nbsp; &nbsp; &nbsp; if (foundCartItem) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return foundCartItem.qty;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; }在您的模板中:<ion-item class="added" *ngFor="let item of getProductsWithQuantity();let key=index;">&nbsp; &nbsp;<span class="count">&nbsp; &nbsp; &nbsp; &nbsp;{{item.qty}}&nbsp; &nbsp;</span>...
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答