You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular 4的*ngFor循环内为文本框设置默认值

解决Angular *ngFor中数量输入框默认值为1的问题

我来帮你搞定这个问题~你的输入框默认值没生效,核心原因是没有把输入框和商品数据做双向绑定,而且没给选中的商品初始化数量属性。下面分步骤来实现:

1. 给选中商品添加并初始化数量属性

首先,你需要确保selectedProd数组里的每个商品对象都有一个quantity属性,并且默认值设为1。具体分两种情况:

情况一:当用户手动添加商品到选中列表时

在组件的添加方法里,给新加入的商品带上quantity:1:

selectedProd: any[] = [];

addToSelected(product: any) {
  // 先检查商品是否已在选中列表,避免重复添加
  const isExist = this.selectedProd.find(item => item.id === product.id);
  if (!isExist) {
    // 用扩展运算符复制原商品属性,再添加quantity默认值
    this.selectedProd.push({...product, quantity: 1});
  }
}

情况二:如果selectedProd是从接口/其他地方获取的

在组件初始化(比如ngOnInit)时,遍历数组给每个商品加上quantity属性:

ngOnInit() {
  // 假设你从接口获取选中商品数据
  this.productService.getSelectedProducts().subscribe(res => {
    this.selectedProd = res.map(prod => ({
      ...prod,
      quantity: 1 // 初始化数量为1
    }));
  });
}

2. 模板中用双向绑定关联输入框

修改你的模板代码,添加数量列,用[(ngModel)]双向绑定商品的quantity属性,这样默认值就会自动显示为1,用户修改后也能同步到组件数据:

<tr *ngFor="let spro of selectedProd; let i = index;">
  <td data-title="Product Name">{{spro.product_description}}</td>
  <td data-title="Unit Price" class="numeric">
    <i class="fa fa-inr"></i> {{spro.unit_price}} <!-- 替换成你的价格字段 -->
  </td>
  <td data-title="Quantity">
    <!-- 双向绑定quantity,设置min="1"防止输入小于1的数 -->
    <input type="number" [(ngModel)]="spro.quantity" min="1" />
  </td>
  <!-- 可选:添加小计列,实时计算总价 -->
  <td data-title="Subtotal" class="numeric">
    <i class="fa fa-inr"></i> {{spro.unit_price * spro.quantity | number:'1.2-2'}}
  </td>
</tr>

3. 别忘了导入FormsModule

因为[(ngModel)]需要依赖Angular的FormsModule,所以要在你的模块文件(比如app.module.ts)里导入它:

import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // 其他已导入的模块(比如BrowserModule)
    FormsModule
  ],
  // ...
})
export class AppModule { }

这样设置后,每个商品的数量输入框默认就会显示1,而且用户修改数量时,组件里的spro.quantity也会跟着更新,方便后续计算总价之类的操作~

内容的提问来源于stack exchange,提问作者user1187

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:36:44