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

Angular动态房型表单异常:输入框共享值的解决方法

问题解决方法

核心原因

你遇到的问题是因为所有动态生成的输入框name属性完全重复,Angular的表单绑定机制会将同名的表单控件识别为同一个实例,导致输入值互相覆盖、共享。

具体修改步骤

1. 修改视图模板,确保每个输入框的name唯一

在*ngFor指令中添加索引变量,用索引给每个输入框的name属性加上唯一后缀:

<table id="rooms">
  <thead>
    <tr>
      <th>Room Type</th>
      <th>Beds</th>
      <th>Q.ty</th>
    </tr>
  </thead>
  <tbody>
    <!-- 添加let i = index获取循环索引,用索引区分name -->
    <tr *ngFor="let room of HotelModel.rooms; let i = index; trackBy: trackByRoomIndex">
      <td><input [(ngModel)]="room.type" name="type-{{i}}" type="text"></td>
      <td><input [(ngModel)]="room.beds" name="beds-{{i}}" type="number" class="smallField"></td>
      <td><input [(ngModel)]="room.qty" name="qty-{{i}}" type="number" class="smallField"></td>
    </tr>
  </tbody> 
    <button type="button" (click)="onAddRoomType()">Add Room Type</button>
  </table>

2. (可选但推荐)添加trackBy函数优化性能

在组件类中添加trackByRoomIndex函数,帮助Angular更高效地识别数组元素变化,避免不必要的DOM重渲染:

export class HotelComponent {
  title = 'numbers-smallstart';

  HotelModel : Hotel = new Hotel();
  rooms = [
    { type: 'Single', beds: 1, qty: 16 },
    { type: 'Double', beds: 2, qty: 32 },
  ];

  ngOnInit() {
    this.HotelModel.rooms = this.rooms;
  }
  
  onAddRoomType() {
    this.HotelModel.rooms.push({ type: '', beds: 0, qty: 0 });
  }

  // 添加trackBy函数
  trackByRoomIndex(index: number, room: any): number {
    return index;
  }
};

额外规范建议

为了代码更严谨,建议给房型定义具体的模型类,替代Array<any>:

export class Room {
  type: string = '';
  beds: number = 0;
  qty: number = 0;
}

修改Hotel模型中的rooms类型:

export class Hotel{
    name : string = "Hotel Roma Sud";
    stars : number = 3;
    rooms : Array<Room> = []
    roomsSold : number = 12000;
    arrivalsPresences : number = 15000;
    presences : number = 23000;
}

添加房型时改为:

onAddRoomType() {
  this.HotelModel.rooms.push(new Room());
}

这样能获得更好的类型检查和代码提示。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:05:32