Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - Get all changed values on FormGroup

Tags:

angular

I'm new with Angular and I'm wondering if we can get all the values that has changed and only those one.

For example,

this.form = this.formBuilder.group({
  name: '',
  age: '',
  city: ''
});

In my html template, I would like to have 3 inputs, one for each formcontrol of my form. I also want to have a button, when I click on it, the resulting action should be sending to my backend only the changed values (PATCH method).

I don't see how we can do this. I've tried with the observable 'valueChanges', but it returns the whole form and I don't see how it can help me.

Any idea ?

Thanks !

like image 356
Darkkrad Avatar asked Nov 22 '18 23:11

Darkkrad


1 Answers

So here's a workaround that I've been using for sometime and it's working.

Suppose you have form of type FormBuilder and the initial values of each part of the form are stored in info obj. For example, our form has only a username and an email.

in ngOnInit, we subscribe to any changes:

this.form.valueChanges.subscribe(dt => this.fieldChanges());

then we implement the method:

fieldChanges() {
    this.anyChanges = false;
    let username = this.form.controls['username'] && this.form.controls['username'].value || '';
    let email = this.form.controls['email'] && this.form.controls['email'].value || '';

    if (this.info['username'] !== username.trim() || this.info['email'] !== email.trim()) {
        this.anyChanges = true;
    }
}

From this code, if there exists any changes, the anyChange property will be set to true. If you separate the conditions, you can access all the changes for individual form control elements. But if you only care about whether there was any changes, you can use a shorter version of the code above, using Object.keys(info).forEach(...) and then you will be able to detect changes in a more generalized and better way. Or if you wish to store the fields that've been changed, you can define an object and in the forEach part, you add the keys and values of the changed fields to this object. At the end, you have an object of changed fields with their old/new values, as needed.

like image 66
imans77 Avatar answered Oct 17 '22 17:10

imans77