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

Angular 如何实现绑定通用键值数组的动态输入字段功能

实现方案

第一步:组件层逻辑定义

你需要额外定义一个临时数组来承载动态输入的键值对,直接操作目标对象做双向绑定灵活性太低,提交时再转成你需要的cost结构即可:

// 原有目标对象,按需调整value的类型
cost: { [key: string]: number | string };
// 动态输入项临时存储数组
costItems: Array<{ key: string, value: number | string }> = [];

// 新增输入对方法
addCostPair() {
  this.costItems.push({ key: '', value: 0 });
}

// 提交时转换为目标对象结构
generateCostObj() {
  this.cost = {};
  this.costItems.forEach(item => {
    // 过滤空键的无效输入项
    if (item.key.trim()) {
      // 如果你需要value统一为数字,这里可加Number()转换,允许字符串则直接赋值
      this.cost[item.key] = item.value;
    }
  });
  // 输出的cost就是你需要的键值对象结构
  console.log(JSON.stringify(this.cost));
}

第二步:模板层ngModel绑定

用*ngFor遍历临时数组渲染输入对,必须给每个input的name属性加唯一标识,否则同name的ngModel会出现绑定冲突:

<!-- 新增输入对按钮 -->
<button type="button" (click)="addCostPair()">新增费用分类</button>

<!-- 动态渲染输入项 -->
<div *ngFor="let item of costItems; let idx = index">
  <input 
    name="costCat-{{idx}}" 
    [(ngModel)]="costItems[idx].key" 
    placeholder="输入分类名"
  />
  <input 
    name="costVal-{{idx}}" 
    [(ngModel)]="costItems[idx].value" 
    placeholder="输入费用值"
  />
</div>

<!-- 提交生成目标对象按钮 -->
<button type="button" (click)="generateCostObj()">提交</button>

可选优化

如果需要支持删除单条输入项,在每一项渲染区域加删除按钮即可:

<button type="button" (click)="costItems.splice(idx, 1)">删除当前项</button>

如果要求费用值必须为数字,给第二个input加type="number"属性即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:00:07