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

循环数组对象属性绑定[(ngModel)]失效问题求助

解决Angular循环mat输入框[(ngModel)]绑定失效问题

嘿,我来帮你搞定这个问题!你遇到的[(ngModel)]绑定没正常工作,大概率是踩了两个常见的Angular表单坑,咱们一步步来修复:

1. 每个输入框的name属性必须唯一

Angular的[(ngModel)]依赖name属性来跟踪每个表单控件的状态,你现在循环里所有输入框的name都是固定的trtrtrtrt,Angular根本没法区分它们对应的模型数据!

解决办法很简单,用*ngFor的索引或者对象的唯一标识来生成动态唯一的name:

<mat-form-field class="example-full-width" *ngFor="let item of test; let index = index">
  <input matInput placeholder="Favorite food" [(ngModel)]='item.name' [name]="'food-input-' + index">
</mat-form-field>

如果你的数组对象有唯一ID(比如id: 1这种),用ID生成name会更可靠:

[name]="'food-input-' + item.id"

2. 确保导入了FormsModule

[(ngModel)]属于Angular的模板驱动表单模块,要是你没在组件所属的模块里导入FormsModule,这个指令根本不会生效!

打开你的模块文件(比如app.module.ts或者对应组件的feature module),添加如下导入:

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

@NgModule({
  declarations: [
    // 你的组件声明
  ],
  imports: [
    // 其他已导入的模块(比如MatInputModule、MatFormFieldModule)
    FormsModule // 一定要加这个!
  ]
})
export class YourModuleName { }

完整示例验证

组件TS代码:

import { Component } from '@angular/core';

@Component({
  selector: 'app-test-inputs',
  templateUrl: './test-inputs.component.html'
})
export class TestInputsComponent {
  test = [{name: 'Harish'},{name: 'Pushpa'}];
}

组件HTML代码(已修复):

<mat-form-field class="example-full-width" *ngFor="let item of test; let index = index">
  <input matInput placeholder="Favorite food" [(ngModel)]='item.name' [name]="'food-' + index">
</mat-form-field>

<!-- 可以加个调试用的输出,看看模型是否同步更新 -->
<pre>{{ test | json }}</pre>

现在你修改输入框内容,应该能看到下方的test数组实时同步变化了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:58:55