Angular 4中如何更新文本框值并实现无刷新保存
无需刷新页面更新编辑后的值的解决方案
嘿,我来帮你搞定这个问题!你现在的情况是:编辑文本框的值并提交到后端后,前端视图没有自动更新,必须刷新页面才能看到新值。这是因为你只完成了后端数据的更新,却没有同步更新前端组件里对应的属性,Angular的视图更新依赖于组件属性的变化,所以咱们只需要在请求成功后手动更新前端数据就行啦。
问题根源
你的现有代码里,EditValue函数只负责把新值提交到后端,但没有修改组件中item_r.remarks的值,所以Angular不知道要更新视图,只有刷新页面重新获取数据时才会显示新值。
修改步骤及代码
1. 更新HTML代码,传递item_r对象到处理函数
在点击事件里把当前的item_r对象传进去,这样我们就能在TypeScript里直接修改它的remarks属性:
<div class="col-sm"> <div *ngIf="item_r.remarks === 'Absence'; else other"> <input [value]="item_r.remarks" #titleInput style="width:100px;text-align: center;"> <span class="glyphicon glyphicon-info-sign" aria-hidden="true" style="color:purple" title="Edit" (click)="EditValue($event, titleInput.value, item_r.log_id, item_r)"> </span> </div> <ng-template #other> {{item_r.remarks}} </ng-template> </div>
注意:移除了无效的
ng-model指令(这是AngularJS的语法,Angular 2+不适用)。
2. 修改TypeScript代码,请求成功后更新前端数据
在HTTP请求的成功回调里,把新的备注值赋给item_r.remarks,触发Angular的变更检测来更新视图:
EditValue(event, newRemark, log_id, item) { console.log(newRemark); console.log(`${newRemark} ${log_id}`); const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); const options = new RequestOptions({ headers: headers }); let body = `log_id=${log_id}&remark=${newRemark}`; console.log(body); this.http_.post('http://localhost:12412/api/employee?', body, options) .subscribe( (data) => { console.log(data); // 请求成功后,同步更新前端的remarks值 item.remarks = newRemark; }, (error) => { // 可选:添加错误处理,提示用户保存失败 console.error('保存失败,请重试:', error); } ); }
3. (可选)优化输入框的双向绑定
如果你希望在输入过程中就同步更新item_r.remarks,可以把输入框的[value]改成双向绑定[(ngModel)],这样就不需要通过#titleInput获取值了,代码会更简洁:
<input [(ngModel)]="item_r.remarks" style="width:100px;text-align: center;">
对应的TypeScript函数可以简化为:
EditValue(event, log_id, item) { const newRemark = item.remarks; console.log(newRemark); console.log(`${newRemark} ${log_id}`); const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); const options = new RequestOptions({ headers: headers }); let body = `log_id=${log_id}&remark=${newRemark}`; console.log(body); this.http_.post('http://localhost:12412/api/employee?', body, options) .subscribe( (data) => { console.log(data); }, (error) => { console.error('保存失败,请重试:', error); } ); }
为什么这样能解决问题?
当你在请求成功后修改item.remarks的值时,Angular的变更检测机制会检测到这个属性变化,自动更新对应的视图——也就是把原来的输入框切换成显示新的备注值,完全不需要刷新页面。
内容的提问来源于stack exchange,提问作者E.L.N.D.Madubhashini
相关产品推荐
相关产品推荐

