问题
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?
回答1:
Each instance of formControl has markAsDirty() and markAsPristine() methods, 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
来源:https://stackoverflow.com/questions/44508982/make-pristine-angular-form-control-dirty