html - 在 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;
}
解决方案
使用带有代码的 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);
}
};
那么它可能会起作用!
推荐阅读
- python - 将 UUID 字段从一个文档复制到另一个丢弃 BinData 类型 - PyMongo
- xml - 如何将实体变量连接到 log4net.config 文件中的值字段?
- swift - 将生成器添加到项目
- wpf - 用作 activex 对象时,WPF 窗口样式不起作用
- linux - 用于移动和重新键入文件的 Shell 脚本
- nextflow - 如何打造档案价值通道?
- html - 防止“float:right” div 占据整个空间
- audio - Wavesurfer 在播放失败时获取错误详细信息
- c# - 如何在后台线程上将 UI 元素序列化为 JSON?
- android - 当我向下滑动或向上滑动时更改运动事件的视图高度