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

如何在ngFor循环中实现按钮仅在对应purchaseCount输入框填值后启用?

解决方案:使用Angular响应式表单的FormArray实现

你当前的问题在于循环渲染时所有输入框都绑定了同一个purchaseCount表单控件,导致无法独立控制每一行的按钮状态。下面是无需ngModel的实现方案,基于Angular响应式表单的FormArray:

1. 组件类代码修改

首先在组件中创建一个FormArray,为每个库存项生成独立的表单组:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';

@Component({
  // 保留你的组件元数据
})
export class YourComponent implements OnInit {
  inventoryList: any[] = []; // 你的库存数据数组
  purchaseFormArray: FormArray;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    // 初始化FormArray,为每个库存项创建包含purchaseCount的FormGroup
    this.purchaseFormArray = this.fb.array(
      this.inventoryList.map(() => 
        this.fb.group({
          purchaseCount: ['', [Validators.required, Validators.min(1), Validators.pattern('^[0-9]*$')]]
        })
      )
    );
  }

  // 获取对应索引的表单组
  getRowForm(index: number): FormGroup {
    return this.purchaseFormArray.at(index) as FormGroup;
  }

  onAdd(item: any, index: number): void {
    const count = this.getRowForm(index).get('purchaseCount').value;
    // 这里处理添加逻辑,比如把item和count加入账单
    console.log('添加商品:', item, '数量:', count);
    // 可选:添加后清空输入框
    this.getRowForm(index).reset({ purchaseCount: '' });
  }
}

2. 模板代码修改

修改模板,绑定FormArray并为每一行关联独立的表单组,同时控制按钮禁用状态:

<form [formGroup]="purchaseFormArray">
  <table class="table table-hover" style="width: 100%;">
    <thead>
      <tr>
        <th>Item</th>
        <th>Stock available</th>
        <th>Price</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of inventoryList; let i = index" [formGroup]="getRowForm(i)">
        <td>{{ item.item }}</td>
        <td>{{ item.count }}</td>
        <td>{{ item.sellingPrice }}</td>
        <td> 
          <button 
            type="button" 
            class="btn btn-primary" 
            style="margin:5px; width:100px" 
            (click)="onAdd(item, i)"
            [disabled]="getRowForm(i).invalid || !getRowForm(i).get('purchaseCount').value"
          >
            Add Item
          </button>
          <input  
            type="number" 
            formControlName="purchaseCount" 
            class="form-control" 
            style="margin:5px; width:100px" 
            placeholder="Count"
            min="1"
          >
        </td>
      </tr>
    </tbody>
  </table>
</form>

关键说明

  • 每个库存项对应FormArray中的一个FormGroup,确保输入框的状态独立可控
  • 按钮的[disabled]绑定到对应表单组的invalid状态,同时判断输入值是否存在,只有当数量填写合法(非空、≥1、纯数字)时才启用按钮
  • 使用响应式表单的验证器(Validators.required、Validators.min(1)等)确保输入的合法性,无需手动判断输入内容

内容的提问来源于stack exchange,提问作者Bharathi Kannan A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:55:18