首页 > 解决方案 > 编辑购物车中的商品

问题描述

我正在构建一个订购披萨的项目,我想按特定顺序编辑披萨的配料。

我有一个选择浇头的按钮。当我单击它时,该按钮变为蓝色。

我的问题是如何添加到返回,选择按钮顶部和蓝色按钮保持蓝色。

例如,我选择洋葱和橄榄的顶部,它们的按钮现在是蓝色的,当我想改变我的选择时,我希望洋葱和橄榄的按钮保持蓝色。

指示

@Directive({
  selector: '[appButton]'
})
export class ButtonDirective  {

  constructor(private elRef: ElementRef, private renderer: Renderer2) {

  }
@HostListener('mousedown') onmousedown() {
   if (this.elRef.nativeElement.style.backgroundColor === 'blue') {
    // console.log(this.elRef.nativeElement);
     this.renderer.setStyle(this.elRef.nativeElement, 'background-color', 'rgba(200,0,0,0.7)');
   } else {
     this.renderer.setStyle(this.elRef.nativeElement, 'background-color', 'blue');

   }
}

html

<div class="row choiceBoxTopping" style="position: relative; top: 90px; padding-top: 10px ">
  <p style="padding-left: 10px">Please choose a Topping</p>
  <app-button *ngFor="let topping of toppings; let i = index"
              [topping]="topping"
              [index]="i"></app-button>
  <button class="btn btn-primary" style=" position:absolute; bottom: 7px; right: 20px" (click)="onContinue()">Continue</button>
</div>

html 应用程序按钮

    <div class="col-md-4" style= "padding-top: 10px;">
    <button id="top" type="button" class="btn btn-danger"  style="width: 110px" appButton (click)= "onClickDown()"  >
      {{topping.name}}
    </button>
    </div>

ts

  onContinue() {

    this.carts = new Cart(this.mealService.getPizzaName(),
      this.mealService.getOrderChoosePrice(), this.mealService.getTopping());
    this.orderService.addItemCart(this.carts);
   }

服务

public addItemCart(cart: Cart) {
  this.cart.push(cart);
  this.cartChanged.next(this.cart.slice());
  this.price += cart.price;
}

标签: javascripthtmlangulartypescript

解决方案


由于您在购物车中保存了浇头列表,您可以使用它添加样式。So when the topping is selected, the you it will be blue, otherwise, it will be red. 这可以使用类来完成。

您可以在 ngOnInit 中查看之前的浇头,并在其中添加一个selected字段

ngOnInit() {
  this.toppings = this.toppings
    // Create new array with selected field;
    .map(topping => {
      // Check if the topping is selected
      const isSelected = this.mealService.getTopping()
        .some(selectedTopping => topping.name === selectedTopping.name);
      topping.selected = isSelected;
      return topping; 
    })
}

在样式表中:

.red {
  background: red;
}

.blue {
  background: blue;
}

在模板中:

<div class="col-md-4" style= "padding-top: 10px;">
  <button type="button" class="btn"  style="width: 110px" (click)= "onClickDown(topping)" 
    [ngClass]="{'red': !topping.selected, 'blue': topping.selected }" >
  {{topping.name}}
  </button>
</div>

onClickDown函数中,您可以更改selected标志

onClickDown(topping) {
  topping.selected = !topping.selected;
}

推荐阅读