【问题标题】:Make pristine Angular form control dirty [duplicate]使原始的Angular表单控件变脏[重复]
【发布时间】:2017-11-14 11:50:16
【问题描述】:

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

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

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

<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 应该只指定人类交互并且不能以编程方式更改,那么这里哪种解决方案更可取?

【问题讨论】:

    标签: javascript angular typescript angular-reactive-forms


    【解决方案1】:

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

    this.form.controls.foo.markAsPristine()
    

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

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

    甚至

    this.form.markAsPristine()
    

    markAsDirty() 方法也可以这样做

    【讨论】:

    • markAsDirty 就像一个魅力!
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2019-11-19
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2018-08-11
    相关资源
    最近更新 更多