Angular(2 +)检测Angular形式的数据(反应性)是否已更改 [英] Angular(2 +) Detect if data in an Angular form (reactive) was changed

查看:66
本文介绍了Angular(2 +)检测Angular形式的数据(反应性)是否已更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some form and button to save it. The button must only be enabled when there are unsaved changes (inputs) on the form.

<form>
    <div>
    ... (inputs)
        <span (click)="save()"> Save </span>
    </div>
</form>

在Angular 5中是否存在一些用于表单脏检查的内置机制?实现此方案的最简单方法是什么?

Is there some build-in mechanism for form dirty check in Angular 5? What is the easiest way to implement this scenario ?

推荐答案

是的,我强烈建议您看一下

Yes there is: I highly advise you to take a look at the documentation of reactive forms.

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

Apart from that, the built-in mechanism is only for checking the state of the form:

  • touched表示用户已输入表格
  • dirty/!pristine表示用户已进行修改
  • touched means the user has entered the form
  • dirty / !pristine means the user has made a modification

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

But if you want to handle changes made, you should not use that: if your username changes its username from "foo", to "bar", then back to "foo", there is no changes in your form, so the user should not have to send the said form.

相反,我建议您做一个函数,将表单与对象的原始值进行比较.这是您的操作方法:

Instead, what I advise you is to make a function that compares the form to the original value of your object. Here is how you can do it:

// 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; }
}

这篇关于Angular(2 +)检测Angular形式的数据(反应性)是否已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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