Angular 15模板绑定问题:saveDeal无法获取更新后的customerId
问题解决:Angular 15模板双向绑定不更新数据
核心问题出在input的双向绑定语法错误,以及缺少必要的模块导入,按以下步骤修复:
1. 替换错误的双向绑定语法
把<input [(value)]="xdossier.customerId" type="text" />改成:
<input [(ngModel)]="xdossier.customerId" type="text" name="customerId" />
注意:
[(ngModel)]在模板驱动表单中需要配合name属性使用,若不想纳入表单管理,也可以添加[ngModelOptions]="{standalone: true}"来独立使用。
2. 确保导入FormsModule
在组件所属的NgModule中导入FormsModule,否则ngModel指令无法生效:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // 导入该模块 import { YourComponent } from './your.component'; @NgModule({ imports: [BrowserModule, FormsModule], // 添加到imports数组 declarations: [YourComponent], bootstrap: [YourComponent] }) export class YourModule { }
3. 优化属性绑定(可选但推荐)
将c-modal的id插值绑定改为属性绑定,这是Angular的最佳实践:
<c-modal #editDealModal [id]="xdossier.id" scrollable size="xl" >
原因说明
[(value)]不是Angular官方支持的双向绑定语法,input元素没有valueChange事件,仅靠它无法实现视图与数据的双向同步。[(ngModel)]是Angular专为表单元素设计的双向绑定指令,会自动监听input事件更新组件数据,同时将组件数据同步到视图,完全适配你的场景。
内容的提问来源于stack exchange,提问作者Jose Manuel Gomez Alvarez
相关产品推荐
相关产品推荐

