首页 > 解决方案 > 在 HTML5 中为 Input 标签初始化变量

问题描述

这是加载产品数组的页面的 html 源代码:

<div class="container" *ngFor="let product of products">
  <div class="product">
    <div class="img-container">
      <img
        //image url
    </div>
    <div class="product-info">
      <div class="product-content">
        <h1>{{product.name}}</h1>
        <p>{{product.description}}</p>
        <p>Price: {{product.price}} $</p>
        <p>Quantity:
          <button type="button" class="btn btn-danger" (click)="minusQuantity(product)">-</button>
          <input type="number" class="input-quantity" [(ngModel)]="product.count"/>
          <button type="button" class="btn btn-success" (click)="plusQuantity(product)">+</button>
        <div class="buttons">
          <a class="button add" (click)="addToCart(product)">Add to Cart</a>
        </div>
      </div>
    </div>
  </div>
</div>

加载页面时,数字输入为空(内部没有可见值)。因此,单击 - 和 + 按钮来调用minusQuantity()并且plusQuantity()对 product.count 没有影响并将其显示在页面上。

我尝试设置默认值,但它被 ngModel 覆盖。如果我只使用没有 ngModel 的值,那么输入不会对 -/+ 按钮引起的任何更改做出反应(因为它只是硬编码的“1”)。

但是,如果我在输入端手动输入例如“1”,那么 + 和 - 按钮确实可以工作,因为提供了一个值,并且可以正常工作。

问题是:

如何避免这个问题?有什么方法可以用一些值初始化输入类型,然后正确地将其传递给 product.count 吗?或者方法应该完全不同?

处理 +/- 方法的组件片段:

product.component.ts

plusQuantity(product: ProductModel) {
   if (product.count < 99) {
     this.cartService.increaseQuantity(product);
   }
 }

 minusQuantity(product: ProductModel) {
   if (product.count > 1) {
     this.cartService.decreaseQuantity(product);
   }
 }

购物车服务.ts

increaseQuantity(product: ProductModel) {
    product.count = product.count + 1;
    this.orderElement.quantity = product.count + 1;
    return product.count;
}

decreaseQuantity(product: ProductModel) {
    product.count = product.count - 1;
    this.orderElement.quantity = product.count - 1;
    return product.count;
}

标签: htmlangular-cli

解决方案


使用带有代码的 javascript 文件:

var cartService = {}
cartService.plusQuantity = function(product) {
    product = ProductModel;
    if (product.count < 99) {
        this.cartService.increaseQuantity(product);
    }
};
cartService.minusQuantity = function(product) {
    product = ProductModel;
    if (product.count > 1) {
        this.cartService.decreaseQuantity(product);
    }
};

那么它可能会起作用!


推荐阅读