简体   繁体   中英

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. 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. 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. 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.

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. You can use 'myForm.dirty' to check the dirty status of the form.

Otherwise, you can set the initial value of the form to an object property using the getRawValue() method

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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