Aakriti.G
Aakriti.G

Reputation: 686

How to change value of current array/ object only using ngmodel angular2

I have an array and an object. In array I am getting a list from my service and in object I am assigning first element of that array.

feesEntries: Array<any> = [];
selectedFeesEntry: any;
clientList: Array<any> = [];

getData(data){
   this.feesEntries = JSON.parse(data['_body']);
   this.selectedFeesEntry = this.feesEntries[0];
}

On UI A table is displayed from the feesEntries array. I have a dropdown to select clients and for options I have ClientList & ngModel is used to bind select to selectedFeesEntry.

Sample:

<label class="control-label" for="select">Client Name</label>
    <div class="input-group">
        <select class="form-control" id="select" [(ngModel)]="selectedFeesEntry.client.name" name="selectedClientName" (change)="onClientNameChange(selectedFeesEntry.client.name)">
          <option *ngFor="let cl of clientList" [ngValue]="cl.name">{{cl.name}}</option>
        </select>
    </div>

Now the issue is when i am selecting a client from the options then using ngmodel only selectedFeesEntry should be updated but in my case feesEntries are also updated. I have no idea why it is happening.

Any help would be appreciated.

Thanks

Upvotes: 0

Views: 1127

Answers (1)

cyberpirate92
cyberpirate92

Reputation: 3166

As far as I understand, When an option is selected from the dropdown, selectedFeesEntry changes and since you have assigned selectedFeesEntry like this,

this.selectedFeesEntry = this.feesEntries[0];

selectedFeesEntry is just a reference to this.feesEntries[0] or in other words, it's a shallow copy

To perform a deep copy,

this.selectedFeesEntry = JSON.parse(JSON.stringify(this.feesEntries[0]));

Which will create a new object

Example: Shallow Copy

Example: Deep copy

Hope this helps

Upvotes: 3

Related Questions