javascript - 编辑购物车中的商品
问题描述
我正在构建一个订购披萨的项目,我想按特定顺序编辑披萨的配料。
我有一个选择浇头的按钮。当我单击它时,该按钮变为蓝色。
我的问题是如何添加到返回,选择按钮顶部和蓝色按钮保持蓝色。
例如,我选择洋葱和橄榄的顶部,它们的按钮现在是蓝色的,当我想改变我的选择时,我希望洋葱和橄榄的按钮保持蓝色。
指示
@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;
}
解决方案
由于您在购物车中保存了浇头列表,您可以使用它添加样式。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;
}
推荐阅读
- google-cloud-bigtable - 我们如何使 cbt 命令可重新运行
- wordpress - 被病毒感染的Wordpress网站;如何备份或恢复?
- python - 使用 selenium 从表中抓取数据
- javascript - 用 vue.js 调用 Nostramap Javascript?
- c++ - 如何访问标准库算法中的类私有成员?C++
- azure - 是否可以将深度学习模型与 Microsoft Bot Framework (SDK) 一起使用?
- erlang - gen_tcp:connect 将在使用 supervisor 时关闭
- python - 即使 DEBUG = True,Django 仍然在 heroku 中的 MEDIA_URL 中添加“app”
- javascript - 加入服务器时,Discord bot 未在默认频道中发送消息
- html - 如何摆脱部分之间的空白?