数据保存后,Angular2 单向绑定表单不会被清除 [英] Angular2 One-way binding form doesn't get cleared after data save

查看:26
本文介绍了数据保存后,Angular2 单向绑定表单不会被清除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,其中输入以单向方式绑定到对象.

I have a form where inputs are bound to object one-way.

<input type="text" name="lastName" #lastName="ngModel" [ngModel]="selectedPers.lastName" required minlength="2">

保存表单时,我读取表单数据并将其发送到服务器,然后使用虚拟/空数据更新我的模型以将其清除.

When saving form I read form data and send it to server, then update my model with dummy/empty data to clear it out.

this.peopleListObservable.push(newPersonFormData).then(a => {
        this.clearPers();
      })


  clearPers() {    
    this.selectedPers = this.dummyPers;
    this.isPersAdd = true;
  }

这个清除方法是独立的,当我通过单击按钮调用它时可以工作,但是如果我在保存承诺中将数据发送到服务器后调用它,则它不起作用/清除表单then方法.任何想法为什么我会遇到这种行为,我该怎么做才能清除我的表格?

This clear-out method is separate and works when I call it from a button click, but it doesn't work/clear form if I call it after sending my data to server in my save promise then method. Any ideas why I experience such behavior and what shall I do to clear out my form?

我已经像这样更改了 clearPers 函数,希望重新加载页面:

I've changed clearPers function like so with hope to reload the page:

  clearPers() {    
    console.log('Inside clearPers function');
   this.router.navigate(['/person/' + this.key]);
  }

猜猜怎么着,控制台日志已打印,但路由器导航没有发生.

guess what, console log is printed but router navigation didn't happen.

我错过了什么?

编辑 2:感谢@FabioAntunes 提醒我路由器的想法无论如何都行不通.

EDIT 2: Thanks @FabioAntunes for reminding me that router idea wouldn't work anyways.

编辑 3:对 Angular 2 RC4 版本的项目提出问题.阅读下面我的回答,了解后来发生的事情,并且应该在 Angular2 的最终版本中发生.

EDIT 3: Question is asked for a project with Angular 2 RC4 release. Read below my answer for what happened later and is supposed to happen in final release of Angular2.

推荐答案

Angular2 Forms 还没有重置选项,如果你阅读了 文档 用于表单,它们为您提供临时修复.

Angular2 Forms don't have the reset option yet, if you read the documentation for the Forms, they give you a temporary fix.

经过反思,我们意识到 Angular 无法区分替换整个英雄和以编程方式清除 name 属性.Angular 不做任何假设,而是让控件处于当前的脏状态.

Upon reflection, we realize that Angular cannot distinguish between replacing the entire hero and clearing the name property programmatically. Angular makes no assumptions and leaves the control in its current, dirty state.

只需在组件的类中添加一个 active 属性,然后在表单上添加一个 ngIf:

Just add an active property to your component's class, then on your form add an ngIf:

然后在你的函数上:

clearPers() {    
  this.selectedPers = this.dummyPers;
  this.isPersAdd = true;
  this.active = false;
  setTimeout(() => this.active = true, 0);
}

setTimeout 位是临时修复:

这是一个临时解决方法,我们正在等待正确的表单重置功能.

This is a temporary workaround while we await a proper form reset feature.

这篇关于数据保存后,Angular2 单向绑定表单不会被清除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆