【问题标题】:Angular2: How change pristine of NgModel in code?Angular2:如何在代码中改变 NgModel 的原始状态?
【发布时间】:2017-04-22 05:30:00
【问题描述】:

当你更改 NgModel 的字段时,它会自动将 model.prisitne 更改为 true。

当你提交表单时,它并没有改变“原始”,毫无疑问,这不是一个错误。

但就我而言,当“原始”为真时显示错误,当我提交表单时,我需要显示验证错误,我认为当您提交表单时,我们可以说此表单中的字段已触及,因为你不能提交无效的表格。但在 Angular2 中,它以不同的方式工作。

那么,有什么方法可以说在代码/组件中触摸了表单控件/字段(pristine = true)?

let email:AbstractControl = this.frm.form.controls['email'];

设置电子邮件“prisitne”为真。

【问题讨论】:

  • 在什么代码中?请将代码添加到您的问题中,以展示您尝试完成的任务、尝试的内容以及失败的地方。
  • 我加了一行代码
  • 我觉得你对质朴和感动有一些错误的理解。 1)两者不一样。2)当你改变输入值时,原始变为假。

标签: validation angular typescript


【解决方案1】:
email.markAsPristine();
email.markAsTouched();
email.reset();

this.frm.reset();

另见https://angular.io/docs/ts/latest/api/forms/index/AbstractControl-class.html

您可以使用这种更短的方法来获取控件

let email:AbstractControl = this.frm.get('email']);

【讨论】:

    【解决方案2】:

    每个表单控件都附加了不同的状态。

    您可以通过以下代码检查任何状态,

    this.frm.form.controls['email'].pristine;
    this.frm.form.controls['email'].touched;
    

    供参考。看看这个 plunker 并点击按钮。

    https://plnkr.co/edit/mJFftirG3ATDpnJRWmKN?p=preview

    【讨论】:

      【解决方案3】:

      从 Angular v4.4.5 开始

      markAsDirty() 移除控制原始状态

      markAsPristine() 将控件设置为原始状态

      【讨论】:

        猜你喜欢
        • 2013-06-15
        • 2016-10-10
        • 1970-01-01
        • 1970-01-01
        • 2016-10-11
        • 2016-10-17
        • 1970-01-01
        • 2021-08-11
        • 2014-02-20
        相关资源
        最近更新 更多