首页 > 解决方案 > Angular2+ - 克隆一个变量并不能阻止改变它

问题描述

我有一个通过@Input()“contactInformation”包含数据的组件。

我希望不能更改contactInformation 的内容。因此我创建了一个克隆,以便没有参考。

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

  public businessArray = [];

  constructor(){
  }

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

如果我通过输入字段更改数据,它也会更改为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>
...

我原以为只有数组会被调整,因为不再引用contactInformation。

我在哪里犯错?

标签: angulartypescript

解决方案


你的数组被克隆了,你的数组中的对象不是。如果它是一个浅对象,您可以执行以下操作:

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

还有很多图书馆可以帮助你解决这个问题


推荐阅读