简体   繁体   English

检测对象何时更改Angular 5

[英]Detect When a object changes Angular 5

I'm trying to detect when ever an object changes. 我试图检测对象何时改变。 The object is connected to a large form. 该对象已连接到大型表单。 Whenever a user changes the input I would like it to have save/cancel buttons popup at the bottom of the page. 每当用户更改输入时,我希望它在页面底部弹出保存/取消按钮。

My idea was to just make a copy of the object and do *ngIf="object !== object_copy" and if they hit cancel set the data equal to the copied object. 我的想法是只复制对象并执行*ngIf="object !== object_copy" ,如果命中了cancel,则将数据设置为复制的对象。 I don't know if this the proper way to do it since I will be using it twice as many variables for a small task, but I've only used angular for a short time. 我不知道这是否正确的方法,因为我将使用两次作为一个小任务很多变量做到这一点,但我只用angular的时间很短。 I can't get this method to work however because when ever I make a type copy the object losses it's type. 但是,我无法使用此方法,因为每当我进行类型复制时,对象都会丢失其类型。

Can someone help me with this or figure out a better way to do this? 有人可以帮我这个忙,还是可以找到一种更好的方法呢?

If you are using a Form, then you could take advantage of Angular's form control, which will tell you anytime a form and any of its values have been altered in any way. 如果您使用的是Form,则可以利用Angular的表单控件,该控件会在任何时候以任何方式更改了表单及其任何值。 Then, you could do something as simple as: 然后,您可以做一些简单的事情:

form.dirty

or even specific fields. 甚至特定领域。 There are tons of things you can do with reactive and template forms from Angular. 您可以使用Angular的反应式和模板表格来做很多事情。

https://angular.io/guide/forms https://angular.io/guide/forms

You have to subscribe an event to handle the change event: 您必须订阅一个事件来处理更改事件:

constructor(private formBuilder: FormBuilder) {
    this.myForm = formBuilder.group({
      name: 'Jose Anibal Rodriguez',
      age: 23
    })

    this.myForm.valueChanges.subscribe(data => {
      console.log('Form changes', data);
    })
  }

It should works. 它应该工作。

ReactiveForm supports the dirty property. ReactiveForm支持dirty属性。 You can use 'myForm.dirty' to check the dirty status of the form. 您可以使用“ myForm.dirty”检查表单的脏状态。

Otherwise, you can set the initial value of the form to an object property using the getRawValue() method 否则,可以使用getRawValue()方法将表单的初始值设置为对象属性。

this.initailFormValue = this.myForm.getRawValue();

Then just subscribe the form changes using 然后只需使用

myForm.valueChanges.subscribe((value) => {

  this.updatedFormValue = this.myForm.getRawValue();

},
(err) => {
//
}
);

Now you have the initial and current form values. 现在您有了初始和当前表单值。 You can compare and do the remaining. 您可以比较并进行其余操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM