Copy of ngModel also gets affected

Viewed 383

I am trying to store all student details by this function. Consider each student has name and an array[] named marks of numbers (For simplicity)

populate(){
    this.service.getAll()
    .subscribe(response=>{
      this.paginatedResponse = response
      this.students = this.paginatedResponse['result']
      this.studentsCopy = this.paginatedResponse['result']
    })
  }

Consider the total options to range from 1 to 10 So I am using a multi-select dropdown (custom component), and feed in the ngModel like this, consider in TS I have made a dictionary kind of array with

 options=[{id:1,text:"one",..... till 10]
<ng-container *ngFor="let student of students;let i = index">
<custom-multiselect
  [items]="options"
  [(ngModel)]="students[i].marks"
  (ngModelChange)="onSelection(i)"
  optionsKey="text"
  optionsValue="id"
></custom-multiselect>
</ng-container>

And I have onSelection to output both this.students.marks, this.studentsCopy.marks

So Initially, let student 1 has name:"Adam", marks:[1,2,3] The multiselect onload initially shows up 1,2,3 highlighted, since the ngModel binding is done, as I select mark:4 for him then for this.students.marks it shows, name:"Adam", marks:[1,2,3,4] which is totally acceptable, But why is this.studentsCopy.marks also showing the same, ngModel is connected to the original data and not the copy right?

[EDIT]: for this,

    console.log(this.routeCopy[index].roles)
    console.log(this.routeCopy[index].roles instanceof Array)
    this.routeCopy[index].roles = this.routeCopy[index].roles.push(333)
    console.log(this.routeCopy[index].roles)

I got (2) [2, 1]

[2] which wen opened says, 0:2 1:333

true 2 -> not an array instead a number

So next time on select it says push is not a function as it got converted to a number? why did the array instance after pushing became a number?

2 Answers

Try like this:

this.studentsCopy = [...this.students]

or,

this.studentsCopy = this.students.map(object => ({ ...object }))

The spread operator (...) can be used to initialize arrays and objects from another array or object without reference ( Deep Copying )

This is you reference issue, you can solved this using lodash

this.studentsCopy = _.cloneDeep(this.paginatedResponse['result']);
Related