[英]How can I translate this JS to Angular2?
我願意在我的 Angular2 應用程序中實現添加到購物車按鈕,目前我可以在 JavaScript/Jquery 中實現; 但是,我不知道如何實現 Angular2。
這是工作代碼的JSfiddle:
$(document).ready(function() {
$(".up").on('click',function(){
var $incdec = $(this).prev();
if ($incdec.val() < $(this).data("max")) {
$incdec.val(parseInt($incdec.val())+1);
}
});
$(".down").on('click',function(){
var $incdec = $(this).next();
if ($incdec.val() > $(this).data("min")) {
$incdec.val(parseInt($incdec.val())-1);
}
});
});
http://jsfiddle.net/mail2asik/M8JTP/
我想做同樣的事情,但在 Angular2 中。
有任何想法嗎?
您可以使用簡單的 javascript 來實現該功能。
export class HelloWorld {
public amount: number = 1;
addToCart() {
this.amount = 1;
}
addItem() {
if (this.amount == 5) {
this.amount = 5;
}
else {
this.amount = this.amount + 1;
};
}
removeItem() {
if (this.amount == 0) {
this.amount = 0;
} else {
this.amount = this.amount - 1;
};
}
}
html:
<button (click)="addToCart()">ADD item</button>
<br>
<br>
<button (click)="removeItem()" class="btnSign">Down</button>
<input type="text" class="incdec" value="{{amount}}"/>
<button (click)="addItem()" class="btnSign">Up</button>
另一種答案是將文本輸入聲明為變量並“直接”更新它
<tr>
<td>
<input type="button" (click)="dec(elem)" value="Down"/>
<input type="text" #elem value="0"/>
<input type="button" (click)="inc(elem)" value="Up"/>
</td>
</tr>
inc(elem)
{
var nItem = parseInt(elem.value);
if(nItem < 5)
{
nItem +=1;
elem.value = nItem;
}
}
dec(elem)
{
var nItem = parseInt(elem.value);
if(nItem > 0)
{
nItem -=1;
elem.value = nItem;
}
}
這是一個工作的Plunker ^^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.