Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: How change pristine of NgModel in code?

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

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

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.

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'];

Set email "prisitne" true.

like image 389
Grigor Aleksanyan Avatar asked Dec 07 '16 10:12

Grigor Aleksanyan


People also ask

How do you set a pristine to a false form?

Using $setPristine will set the $pristine property of the form to true and $dirty to false. $setDirty will do the contrary.

What is pristine in Angular reactive form?

A control is pristine if the user has not yet changed the value in the UI. A control is dirty if the user has changed the value in the UI. True if the control is marked as touched .

How do I enable ngModel directive?

This directive is used by itself or as part of a larger form. Use the ngModel selector to activate it. It accepts a domain model as an optional Input . If you have a one-way binding to ngModel with [] syntax, changing the domain model's value in the component class sets the value in the view.


1 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 get a control

let email:AbstractControl = this.frm.get('email']);
like image 188
Günter Zöchbauer Avatar answered Sep 21 '22 17:09

Günter Zöchbauer