【问题标题】:Resetting an Angular form with a model使用模型重置 Angular 表单
【发布时间】:2020-01-26 03:36:01
【问题描述】:

我希望能够使用其模型的一些默认值重置 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' };
}

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

我能想到的唯一两件事是使用超时,就像我们过去使用类似污染我们的 AngularJs 应用程序一样

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

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

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

我不太喜欢这两个选项。

我已经尝试给输入一个值,所以重置有一个默认值,但 Angular 仍然将模型设置为 null,即使输入确实有重置设置的文本。

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

【问题讨论】:

    标签: angular angular-template-form


    【解决方案1】:

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

    export class Model{
    text: string;
    }
    

    然后将您的模型分配给该类的新实例

    model = new Model();
    

    然后在你的表单中连接到这个模型对象

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

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

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

    【讨论】:

    • 这并不能解决问题,它与使用对象没有什么不同
    【解决方案2】:

    有一种方法不用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 类型不起作用。我会进行更多研究,希望能找到原因......

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

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

    您通常应该避免在表单中包含重置按钮。它们很少有用,反而更有可能让误点击它们的用户感到沮丧(通常是在尝试点击提交按钮时)。

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

    【讨论】:

      猜你喜欢
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 2015-06-25
      • 2014-06-06
      • 2014-05-29
      • 1970-01-01
      • 2017-05-14
      相关资源
      最近更新 更多