Pascal
Pascal

Reputation: 380

Angular2+ - Cloning a variable does not prevent from changing it

I have a component that contains data via @Input() "contactInformation".

I would like that the content of contactInformation cannot be changed. Therefore I create a clone so that there is no reference.

export class ContactInformationComponent implements OnIni {
  @Input() contactInformation: ContactInformationModel;

  public businessArray = [];

  constructor(){
  }

  ngOnInit() {
    this.businessArray = [...this.contactInformation.business];
  }

If I change the data via an input field, it will also be changed to contactInformation.

<tr *ngFor="let item of businessArray; let i=index">
  <td>
   <div *ngIf="!isEditingInt"
        id="{{configParams[1].key}}">{{getLabeTOUCH_POINT_OPTIONS)}}</div>
   <div *ngIf="isEditingInt">
     <div class="d-inline-block">
        <input class="form-control"
         name="contact_name_{{i}}"
         [required]="configParams[2].required"
         [(ngModel)]="item.contactName">
     </div>
   </div>
  </td>
 </tr>
...

I would have expected that only the array would be adjusted because there is no more reference to contactInformation.

Where do I make the mistake?

Upvotes: 0

Views: 84

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71891

Your array is cloned, the objects in your array are not. If it's a shallow object, you can do the following:

ngOnInit() {
  this.businessArray = [...this.contactInformation.business].map((data) => ({ ...data }));
}

There are also a lot of libraries which can help you with this

Upvotes: 1

Related Questions