如何将此JS翻译成Angular2

How can I translate this JS to Angular2?

本文关键字:翻译 Angular2 JS      更新时间:2023-09-26

我愿意在我的Angular2应用程序中实现添加到购物车按钮,目前我可以在JavaScript/Jquery中实现;然而,我不知道如何做到这一点。

这是一个工作代码的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/

我也想这么做,但在安格拉。

有什么想法吗?

另一种答案是将文本输入声明为变量并"直接"更新

HTML"组件模板"

<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>

JS

      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^^

您可以使用简单的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>   

以下是plunker 中的示例