0

I have 2 properties and I want to set the properties in my http call. But, when I change the data in one property it seems to reflect the changes in the other property as well. My goal is to set both properties but only change the data in on so I can compare the data to see what has changed. I'm using Angular 11

Properties:

myProperty: any[];
myOtherProperty: any[];

The service call:

this.myService.getData(this.query)
      .subscribe(response => {
        this.myProperty= response.result;   ***//Changes to this property seem to reflect in myOtherProperty***
        this.myOtherProperty = response.result; ***//I wanted this to be unchanged so I can compare this to "myProperty" to see what has changed.***
      },
        (error) => {
          console.log(error);
          return of(null);
        }
      );

then if I assign this to a grid/table with editable fields, the changes reflect in "myOtherProperty".

Code for the grid/table:

 <tr *ngFor="let prop of myProperty; let i = index">
 
 <td>
   <textarea class="form-control" aria-label="With textarea" (keyup)="changeValue(i, 'comments', $event)" (blur)="updateList(i, 'comments', $event)">{{ prop.comments }}</textarea>
   </td>
 </tr>
Dennis
  • 93
  • 9

2 Answers2

2

This is pass-by-reference/pass-by-value issue.

response.result might be reference type(Array|Object). As you're assigning the reference type, mutating one property might effect other property. Try using deep cloning the result.

this.myProperty= JSON.parse(JSON.stringify(response.result));
this.myOtherProperty = JSON.parse(JSON.stringify(response.result));

or

Using lib lodash.cloneDeep

this.myProperty= lodash.cloneDeep(response.result);
this.myOtherProperty = lodash.cloneDeep(response.result);

This answer give you more information about pass-by-value and pass-by-reference in JavaScript pass-by-reference or pass-by-value language

Naren
  • 4,152
  • 3
  • 17
  • 28
0
this.myService.getData(this.query)
      .subscribe(response => {
        this.myProperty = JSON.stringify(response.result); // This should do
        this.myOtherProperty = response.result; ***//I wanted this to be unchanged so I can compare this to "myProperty" to see what has changed.***
      },
        (error) => {
          console.log(error);
          return of(null);
        }
      );
saidutt
  • 289
  • 1
  • 7