Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make pristine Angular form control dirty [duplicate]

There is a reactive form in Angular 4, and some control is supposed to be set programmatically at some point.

this.form = formBuilder.group({
  foo: ''
});
...
this.form.controls.foo.setValue('foo');

How can control pristine/dirty state be affected? Currently I'm using both form and foo pristine states, something like:

<form [formGroup]="form">
  <input [formControl]="form.controls.foo">
</form>

<p *ngIf="form.controls.foo.pristine">
  {{ form.controls.foo.errors | json }}
</p>

<button [disabled]="form.pristine">Submit</button>

If pristine/dirty is supposed to designate only human interaction and can't be changed programmatically, what solution would be preferable here?

like image 352
Estus Flask Avatar asked Jun 12 '17 21:06

Estus Flask


1 Answers

Each instance of formControl has markAsDirty() and markAsPristine() methods (inherited from AbstractControl), so, you should be able to run

this.form.controls.foo.markAsPristine()

or better, using reactive forms API:

this.form.get('foo').markAsPristine()

or even

this.form.markAsPristine()

the same may be done with markAsDirty() method

like image 139
Andriy Avatar answered Oct 05 '22 02:10

Andriy