Angular2 单向绑定表单在数据保存后不会被清除

Angular2 One-way binding form doesn't get cleared after data save

我有一种表单,其中输入单向绑定到对象。

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

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

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


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

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

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

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

你猜怎么着,打印了控制台日志,但没有进行路由器导航。

我错过了什么?

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

编辑 3: 问题是针对 Angular 2 RC4 版本的项目。阅读下面我对后来发生的事情的回答,并且应该在 Angular2.

的最终版本中发生

我觉得你的语法有点不对劲。您没有使用输入语法进行一种或两种方式的数据绑定。试试这个来进行双向数据绑定:

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

此外,您不需要这个:#lastName="ngModel"

如果您想以一种方式进行数据绑定(您不能用它来清除控件),请使用此方法:

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

Angular2 Forms 还没有重置选项,如果你阅读 documentation for the Forms,他们会给你一个临时修复。

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 属性 添加到组件的 class,然后在表单上添加 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.

在使用了 Fabio 的回答中描述的方法之后,我决定回到我最初的想法,使用路由参数来刷新我的组件,这在术语中刷新了我的表单。使用 *ngIf 重新创建表单似乎是合乎逻辑的,因为我们目前没有(Angular2 的 RC4)重置表单的自然方式,但是由于某种原因,超时后重新创建会导致我刷新整个页面零件。 我不想花更多时间来修复一个感觉不太自然的解决方案。

在 Whosebug 中寻找其他答案时,我 运行 进入了

来自@angular-university 和@jp-att 的回答揭示了 RC5 有一个修复,form.reset() 方法。不幸的是,我现在无法立即将我的项目移植到 RC5。

所以我回到了我最初的想法(直到我将我的应用程序移植到 RC5/final),使用路由来刷新组件。

首先我尝试使用查询参数,

this.router.navigate(['person/' + this.idKey],{ queryParams: { timestamp: nowTimeNumber}});

这没有帮助,可能是因为同样的原因,它不会帮助使用未绑定到组件中任何模型的路由参数:Angular 的更改检测不会触发如果该更改不影响任何内容,请刷新您的组件(至少这是我的猜测)。查询参数也粘在 url 上,非常难看只是为了刷新技巧。

所以我这样做了: 我创建了一个新的子路由

{ path: 'person/:personid', component: PersonEditComponent},
{ path: 'person/:personid/:timestamp', component: PersonEditComponent}

读取(观察)时间戳,当我需要清除表单数据时来回:

  clearPersonDataRouted(){
    let newTime = moment().unix();
    if(this.timeRouteParam)
    this.router.navigate(['person/'+ this.idKey]);
    else
    this.router.navigate(['person/'+ this.idKey + '/' + newTime]);
  }