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

Angular 5中*ngFor内输入框双向绑定失效问题排查

解决Angular 5中*ngFor内输入框双向绑定失效的问题

嘿,我一眼就揪出问题所在啦——你把Angular双向绑定的语法写反了!

Angular的双向绑定是标准的[(ngModel)]写法(开发者圈内戏称“香蕉在盒子里”),而你写成了([ngModel]),这个顺序错误直接导致输入框的内容没法同步到participant.name属性里,所以提交到后端时name字段始终是初始的空字符串。

具体修正步骤

1. 修复双向绑定语法

把HTML模板里输入框的绑定代码修正过来:

<div class="CreateSettleParticipantBlock"> 
  <h1>Participants</h1> 
  <div class="form-group" *ngFor="let participant of model.participants; let i = index"> 
    <label for="name">Person {{ i + 1 }}</label> 
    <input type="text" class="form-control" id="participant{{i}}" name="participant{{i}}" [(ngModel)]="participant.name"> 
  </div> 
  <button type="button" class="btn btn-info" (click)="addNewParticipant()">Add new person</button> 
</div>

2. 确认FormsModule已正确导入

使用ngModel必须依赖FormsModule,请检查你的模块(比如AppModule或者当前组件所属的Feature Module)是否已经导入了它:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // 引入FormsModule

import { CreateComponent } from './create.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule // 添加到imports数组中
  ],
  declarations: [CreateComponent],
  bootstrap: [CreateComponent]
})
export class AppModule { }

3. 验证Participant类的构造逻辑

最后确认你的Participant类构造函数能正确初始化name属性,比如应该是这样的:

export class Participant {
  constructor(public name: string) { }
}

这样new Participant('')才能生成一个带有空name属性的实例,确保绑定逻辑能正常工作。

修正后的效果

完成以上调整后,你在输入框中填写的参与者名称就会实时同步到model.participants对应的name字段里,提交到后端的JSON数据中就能看到正确的name值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:13:29