首页 文章

使用Angular 6 ngFor,如何在与其他数据数据进行比较时更改某些内容?

提问于
浏览
0

我正在创建购物车 . 我有产品数据的对象数组和购物车项目数据的数组 . 我尝试构建按钮购买项目,有条件按钮,如果相同的产品在购物车数据,然后需要显示'+ 3 -'(数量来自购物车数据的Id),如果产品不在购物车,然后只需显示'buy'按钮 . 我在https://stackblitz.com/edit/angular-267ern上实现的这个相关问题 .

我尝试解决:

  • 管道,

  • trackBy,

  • 尝试更改产品阵列数据图并返回与购物车数据相比较的值(这是为了尝试获得解决方案,但我不能) . 这里使用管道可能在复杂性方面存在一些问题(n * 2) .

因此寻找解决方案以降低复杂性并至少解决此问题 . 如果可能,请注意复杂性 .

1 回答

  • 1

    我想我理解你的问题,这就是你想要的吗?

    在TS中(从stackblitz复制它)

    export class AppComponent {
          products :product[]= [
            { name: 'Radio', price: 34, _id: '12345' },
            { name: 'TV', price: 44, _id: '12346' },
            { name: 'Bascket', price: 16, _id: '12347' },
            { name: 'Banana', price: 4, _id: '12348' },
            { name: 'Bike', price: 5000, _id: '12349' },
            { name: 'Toast', price: 5, _id: '12350' },
            { name: 'Shirt', price: 17, _id: '12351' }
          ];
        isCart (id){
        return this.cart.findIndex((x)=>x._id == id)>=0;
        }
        quantity(id){
        return this.cart.find((x)=>x._id == id).quantity;
        }
        buy(prod:product){
      if(this.cart.findIndex((x)=>x._id == prod._id)<0){
    this.cart.push({name:prod.name,price:prod.price,_id:prod._id,quantity:1})
      }else{ 
    let prod1 = this.cart.find((x)=>x._id == prod._id);
    prod1.quantity +=1;
      }
    
    }
          cart = [
            { name: 'Radio', price: 34, _id: '12345', quantity: 5 },
            { name: 'Toast', price: 5, _id: '12350', quantity: 1 },
          ]
        }
        export interface product{
        name:string;
        price:number;
        _id:string;
        }
    

    并在HTML中:

    <label *ngFor="let item of products">
      <span>
          <p>Name: {{item?.name}}, Price: {{item?.price}}</p>
      </span>
      <button  (click)="buy(item)">
        <span>{{isCart(item._id)?quantity(item._id)+'-':'Buy'}} 
      </span>
      </button>
    </label>
    

相关问题