Make pristine Angular form control dirty [duplicate]

这一生的挚爱 提交于 2019-12-10 12:44:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!