Angular 8表单输入数量时自动计算单条商品总价的实现方案
实现步骤
1. 导入依赖(未导入时需要添加)
在当前功能所属Module中导入FormsModule,用于支持双向数据绑定:
import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ // 其他已有导入项 FormsModule ] }) export class YourModule { }
2. 修改TS代码
获取商品属性数据后,给每个属性条目新增quantity字段存储用户输入的数量,默认值设为0避免计算时报错:
filteredProductAttributeItems: any[] = []; clickToExpandAttItems(product) { this.productService.getProductAttributesItems(product.Id).subscribe(x => { // 遍历数据为每个属性项初始化数量字段 x.forEach(attGroup => { attGroup.ProductAttributeItems.forEach(att => { att.quantity = 0; }) }) Object.assign(this.filteredProductAttributeItems, x); }); }
3. 修改HTML代码
给输入框绑定双向数据绑定,最后一列直接展示计算后的总价:
<ng-container *ngFor="let attItems of filteredProductAttributeItems; let i = index"> <tr> <td [attr.rowspan]="attItems.ProductAttributeItems.length + 1">{{ attItems.Name }}</td> </tr> <tr *ngFor="let att of attItems.ProductAttributeItems"> <td>{{ att.MasterProductAttributeItem.Name }}</td> <td>{{ att.PriceAdjustment }}</td> <td style="width: 15%; white-space: nowrap"> <input type="number" class="form-control form-control-sm" placeholder="Quantity" min="0" [(ngModel)]="att.quantity" /> </td> <td>{{ (+att.PriceAdjustment * (att.quantity || 0)).toFixed(2) }}</td> </tr> </ng-container>
代码中的toFixed(2)用于保留两位小数展示,不需要可以直接删除;+att.PriceAdjustment是为了兼容价格为字符串类型的场景,如果本身是数字类型可以去掉前面的+。
内容的提问来源于stack exchange,提问作者Jason
相关产品推荐
相关产品推荐

