Angular2: How to change the initial version of NgModel in code?

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

When you submit a form, it does not change the "original", not a question, this is not a mistake.

But in my case, I show errors when the “untouched” is true, and when I submit the form, I need to show validation errors, and I think that when you submit the form, we can say that the fields in this form were touching, because you cannot submit an invalid form. But in Angular2, it works differently.

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

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

Set the email address "prisitne" true.

+5
source share
3 answers
 email.markAsPristine(); email.markAsTouched(); email.reset(); 

or

 this.frm.reset(); 

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

You can use this shorter method to gain control.

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

each control has its own different states.

you can check any status with the following code,

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

For reference. check this plunker and press the button.

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

+4
source

As of Angular v4.4.5

markAsDirty() removes a clean control state

markAsPristine() sets control intact

0
source

Source: https://habr.com/ru/post/1260921/


All Articles