Angular2:如何在代码中更改NgModel的原始状态? [英] Angular2: How change pristine of NgModel in code?

查看:57
本文介绍了Angular2:如何在代码中更改NgModel的原始状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When you change the field of NgModel, it automatically change model.prisitne to true.

提交表单时,它不会更改原始"表单,毫无疑问,这不是bug.

When you submit the form, it does't change the "pristine", no question, this is not a bug.

但是在我的情况下,当原始"为真且提交表单时,我会显示错误,我需要显示验证错误,并且我认为当您提交表单时,我们可以说此表单中的字段已被触摸,因为您不能提交无效的表格.但是在Angular2中,它以不同的方式工作.

But in my case, I show errors when "pristine" is true and when I submit the form, I need to show validation errors and I think when you submit the form, we can say that the fields in this form touched, because you can't submit the invalid form. But in Angular2 it works in different way.

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

So, any way to say that the form controls/fields is touched (pristine = true) in code/component?

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

将电子邮件设置为"prisitne".

Set email "prisitne" true.

推荐答案

email.markAsPristine();
email.markAsTouched();
email.reset();

this.frm.reset();

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

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

You can use this shorter method to get a control

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

这篇关于Angular2:如何在代码中更改NgModel的原始状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆