使用模型重置 Angular 表单

Resetting an Angular form with a model

我希望能够使用其模型的一些默认值重置 Angular 表单

<form>
  <input type="text" name="text" [(ngModel)]="model.text">
  <button type="reset" (click)="resetModel()">Reset</button>
</form>

并在组件中

model = { text: 'Test' };

resetModel() {
  this.model = { text: 'Test' };
}

这不起作用,因为重置发生在模型设置好且文本通过重置设置为空之后。

我唯一能弄清楚的两件事是使用超时,就像我们过去用 like

污染我们的 AngularJs 应用程序一样
resetModel() {
  setTimeout(() => { this.model = { text: 'Test' }; });
}

https://stackblitz.com/edit/angular-5pdpml

或者将按钮设为普通的旧按钮而不是重置按钮,并将表单传递给重置方法并调用 markAsUntouched 和 markAsPristine。

我不太喜欢这两个选项。

我已尝试为输入提供一个值,以便重置具有默认值,但 Angular 仍然将模型设置为空,即使输入确实具有重置设置的文本。

有没有办法让重置按钮设置默认表单状态而不是将所有绑定设置为空?

您可以为您的模型创建一个新的 class:

export class Model{
text: string;
}

然后将您的模型分配给 class

的新实例
model = new Model();

然后在您的表单中连接到此模型对象

<form>
  <input type="text" name="text" [(ngModel)]="model.text">
  <button type="reset" (click)="resetModel()">Reset</button>
</form>

要在您的控制器中重置它,请将模型对象设置为新实例

resetForm(){
model = new Model();
}

有一种不用setTimeout的方法。您可以获得表单的引用并调用 resetresetForm 方法(在这种情况下两者都可以)来重置值(和状态)。

<form #myForm="ngForm">
  <input type="text" name="text" [(ngModel)]="model.text">
  <button type="button" (click)="myForm.reset({ text: 'Test' })">Reset</button>
  <!-- <button type="button" (click)="myForm.resetForm({ text: 'Test' })">Reset</button> -->
</form>
{{ model | json }}

这是更新后的 stackblitz

您应该注意到该按钮不是 reset 类型,而是常规 button 类型,由于某种原因,reset 类型不起作用。我将进行更多研究,并希望找到原因...

EDIT:显然,当使用按钮 type=reset 时,它会自动将表单值重置为其默认值(在 input 控件的情况下是 value 属性中定义的值)。这在 Angular 表单上下文中似乎不正确,不应使用(更多关于 here)。

此外,甚至不建议在表单中使用 reset 按钮(根据 official documentation),因此我非常有信心在这种情况下使用 type=button 是正确的。

You should usually avoid including reset buttons in your forms. They're rarely useful, and are instead more likely to frustrate users who click them by mistake (often while trying to click the submit button).

最后提一下resetresetForm的区别。它们是相同的,只是 resetForm 也会影响表单的 submitted 状态(将其设置为 false)。更多关于 here.