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

Angular表格数量输入框仅支持1位输入的修复及focusout事件问题排查

解决方案

1. 让数量输入框支持最多2个字符

给输入框添加maxlength="2"属性,同时推荐将输入类型改为number(仅允许数字输入);若需兼容部分对number类型maxlength支持不佳的浏览器,可保留text类型并添加正则限制数字输入:

优化后的输入框代码

<td>
  <!-- 推荐方案:number类型+长度限制 -->
  <input 
    type="number" 
    [(ngModel)]="p.quantity" 
    maxlength="2"
    (ngModelChange)="updateTotalPrice(p)"
    min="1"
  />
  <!-- 备选方案:text类型+正则限制数字输入 -->
  <!-- <input 
    type="text" 
    [(ngModel)]="p.quantity" 
    maxlength="2"
    (ngModelChange)="updateTotalPrice(p)"
    pattern="[0-9]*"
  /> -->
</td>

2. 修复event.data undefined的问题

原(input)事件中event.data仅在输入新字符时有效,删除字符或粘贴内容时会出现undefined。改用Angular双向数据绑定[(ngModel)]配合(ngModelChange)事件,直接获取绑定的商品数量值,无需依赖不稳定的event.data:

修正后的事件处理函数

updateTotalPrice(product: ProductSelection) {
  // 确保数量为合法正整数,避免非数字输入导致计算错误
  const validQuantity = Math.max(1, Number(product.quantity) || 1);
  product.quantity = validQuantity;
  product.totalPrice = product.itemPrice * validQuantity;
}

3. 替代StackBlitz的本地测试方案

无法访问在线沙箱时,直接搭建本地Angular项目测试:

  • 安装Angular CLI:npm install -g @angular/cli
  • 创建新项目:ng new product-demo
  • 进入项目目录:cd product-demo
  • 将组件代码替换到src/app/app.component.ts和src/app/app.component.html
  • 启动本地服务:ng serve,访问http://localhost:4200即可测试

4. 修正现有代码的其他错误

  • 构造函数中对象字面量属性赋值错误:将id = 1改为id: 1
  • checkout方法中foreach拼写错误:改为forEach
  • 表格中多余的/td>标签:删除重复的闭合标签

完整修正后的代码

TypeScript类与组件代码

export class ProductSelection {
  id!: number;
  name!: string;
  itemPrice!: number;
  quantity!: number;
  totalPrice!: number;
}

// 组件代码
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  products: ProductSelection[] = [];

  constructor() {
    this.products = [
      { id: 1, name: "name1", itemPrice: 3, quantity: 3, totalPrice: 9 },
      { id: 2, name: "name2", itemPrice: 1, quantity: 10, totalPrice: 10 },
      { id: 3, name: "name3", itemPrice: 4, quantity: 4, totalPrice: 16 }
    ];
  }

  updateTotalPrice(product: ProductSelection) {
    const validQuantity = Math.max(1, Number(product.quantity) || 1);
    product.quantity = validQuantity;
    product.totalPrice = product.itemPrice * validQuantity;
  }

  checkout() {
    let total = 0;
    this.products.forEach(i => total += i.totalPrice);
    console.log('结算总价:', total);
    // 调用服务提交数据
  }
}

HTML模板代码

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>ItemPrice</th>
      <th>Quantity</th>
      <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let p of products; let i = index">
      <td>{{ p.name }}</td>
      <td>{{ p.itemPrice }}</td>
      <td>
        <input 
          type="number" 
          [(ngModel)]="p.quantity" 
          maxlength="2"
          (ngModelChange)="updateTotalPrice(p)"
          min="1"
        />
      </td>
      <td>{{ p.totalPrice }}</td>
    </tr>
  </tbody>
</table>

<div>
  <input type="button" (click)="checkout()" value="submit" />
</div>

注意:使用[(ngModel)]需在模块中导入FormsModule,在app.module.ts中添加:

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

@NgModule({
  imports: [
    BrowserModule,
    FormsModule // 加入此行
  ],
  // ...其他配置
})
export class AppModule { }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:39:51