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

查看:93
本文介绍了保存数据后不会清除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.

我想念什么?

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

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

对于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 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:

<form *ngIf="active">

然后在您的函数上:

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天全站免登陆