使原始的 Angular 表单控件变脏 [英] Make pristine Angular form control dirty

查看:13
本文介绍了使原始的 Angular 表单控件变脏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular 4 中有一个响应式形式,一些控件应该在某个时候以编程方式设置.

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

如何控制原始/脏状态?目前我同时使用 formfoo 原始状态,例如:

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>

如果 pristine/dirty 应该只指定人机交互并且不能以编程方式更改,那么这里有什么解决方案更可取?

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

推荐答案

formControl 的每个实例都有 markAsDirty()markAsPristine()方法(从 AbstractControl 继承),因此,您应该能够运行

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

this.form.controls.foo.markAsPristine()

或者更好,使用反应式表单 API:

or better, using reactive forms API:

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

甚至

this.form.markAsPristine()

同样可以使用 markAsDirty() 方法

这篇关于使原始的 Angular 表单控件变脏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆