Angular 5 Form脏支票

All*_*ool 7 html javascript angular angular5

我有一些表格和按钮来保存它。仅当表单上有未保存的更改(输入)时,才必须启用该按钮。

<form>
    <div>
    ... (inputs)
        <span (click)="save()"> Save </span>
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

Angular 5中有一些内置的表单脏检查机制吗?实施此方案的最简单方法是什么?

小智 11

是的,有:我强烈建议您看一下反应形式文档

除此之外,内置机制仅用于检查表单的状态:

  • touched 表示用户已输入表格
  • dirty/ !pristine表示用户已进行修改

但是,如果要处理所做的更改,则不应使用该方法:如果您的用户名将其用户名从“ foo”更改为“ bar”,然后又更改为“ foo”,则您的表单没有任何更改,因此用户应该不必发送上述表格。

相反,我建议您做一个函数,将表单与对象的原始值进行比较。这是您可以做到的:

// Creates a reference of your initial value
createReference(obj: any) {
  this.reference = Object.assign({}, obj);
}

// Returns true if the user has changed the value in the form
isDifferent(obj: any, prop: string) {
  return this.reference[prop] !== obj[prop];
}

submitForm(form: any) {
  // ... Business code ...
  hasChanges = false;
  for (let prop in form) {
    if (this.isDifferent(form, prop)) { hasChanges = true; }
  }
  // If no changes, cancel form submition
  if (!hasChanges) { return; }
}
Run Code Online (Sandbox Code Playgroud)

  • 该解决方案可以在 ngOnChanges() 期间应用,而不是在提交单击期间应用。反应式表单包含一个 valueChanges() 方法,该方法返回一个可观察值,如下所述:https://alligator.io/angular/reactive-forms-valuechanges/。文章写于2017年。 (2认同)

Chr*_*ris 7

当您使用反应式表单(https://angular.io/guide/reactive-forms)时,表单组和控件上都有一个属性pristine和一个属性dirty。应该看起来像这样:

<form form-group="myGroup">
  <div>
    <input type="text" formControlName="ctrl1">
    ... (further inputs)

    <span><button (click)="save()" [disabled]="myGroup.pristine"> Save </button></span>
  </div>
</form>
Run Code Online (Sandbox Code Playgroud)

和.ts文件:

import { Component, .... } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({...})
export class YourFancyComponent {
  myGroup: FormGroup;
  constructor(private( formBuilder: FormBuilder) {
      this.myGroup = this.formBuilder.group({
        'ctrl1': 'defValue',
        'ctrl2': 'defaultValue2'
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

对于模板驱动的表单(根据https://angular.io/guide/forms#track-control-state-and-validity-with-ngmodel),修改后的输入控件的css类从更改为ng-pristineng-dirty但没有更改帮助保存按钮。