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

Angular中如何在ngFor循环中使用ngModel正确绑定数组?

实现步骤

  • 第一步:确保导入FormsModule
    要使用ngModel双向绑定,需要先在根模块(通常是app.module.ts)中导入FormsModule:
    import { FormsModule } from '@angular/forms';
    @NgModule({
      imports: [
        // 其他导入
        FormsModule
      ]
    })
    export class AppModule { }
    
  • 第二步:给循环内的输入框添加唯一name属性
    Angular表单中使用ngModel时,每个输入控件必须有全局唯一的name属性,否则会出现绑定冲突、输入值串位的问题。我们可以用行索引+日期拼接出唯一值,修正后的模板代码如下:
    <mat-card class="hours">
    <table id="customers">
        <thead>
            <th>项目</th>
            <th *ngFor="let day of weeks">{{day | titlecase}}</th>
            <th>总工时</th>
            <th></th>
        </thead>
        <tbody>
          <tr *ngFor="let employee of projectTasks; let i = index">
              <td>{{employee.Project}}</td>
              <td *ngFor="let day of weekdays">
                  <input type="number" [id]="day" [name]="'hours_'+i+'_'+day" [(ngModel)]="employee[day]" class="hours-input">
              </td>
              <td class="total-cell">{{getTotalHours(employee)}}</td>
              <td>
                <button mat-icon-button class="codered" (click)="deleteproject(employee, i)">
                    <mat-icon>delete</mat-icon>
                </button>
            </td>
          </tr>
        </tbody>
    </table>
    <button mat-raised-button color="primary" class="submit" (click)="CreateTimeSheet()">提交</button>
    
  • 第三步:确认weekdays数组定义和对象键名完全匹配
    TS中weekdays的取值必须和你添加项目时的日期键完全一致,示例如下:
    // TS中定义weekdays
    weekdays = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday'];
    // 总工时计算方法示例
    getTotalHours(employee: any): number {
      return this.weekdays.reduce((sum, day) => sum + (Number(employee[day]) || 0), 0);
    }
    // 提交方法直接取projectTasks即可,所有输入值已经被ngModel实时更新到数组中
    CreateTimeSheet() {
      console.log('要提交的所有工时数据:', this.projectTasks);
      // 后续调用接口提交数据逻辑
    }
    

你现有的addProject方法逻辑无需调整,新增的项目条目会自动在模板中渲染,绑定逻辑完全通用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:24:05