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

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

问题描述

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

<div>...(输入)<span (click)="save()">保存 </span>

</表单>

Angular 5 中是否有一些内置的表单脏检查机制?实现此场景的最简单方法是什么?

解决方案

是的:我强烈建议您查看 反应形式的文档.

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

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

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

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

//创建初始值的引用创建引用(对象:任何){this.reference = Object.assign({}, obj);}//如果用户更改了表单中的值,则返回 trueisDifferent(obj: any, prop: string) {返回 this.reference[prop] !== obj[prop];}提交表格(表格:任何){//... 业务代码 ...hasChanges = false;for (let prop in form) {if (this.isDifferent(form, prop)) { hasChanges = true;}}//如果没有变化,取消表单提交如果(!hasChanges){ 返回;}}

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>

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 means the user has entered the form
  • dirty / !pristine means the user has made a modification

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天全站免登陆