首页 > 解决方案 > ngModel 的副本也会受到影响

问题描述

我正在尝试通过此功能存储所有学生的详细信息。考虑每个学生都有name一个array[]命名的数字标记(为简单起见)

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

考虑从 1 到 10 的总选项所以我正在使用一个multi-select dropdown(自定义组件),并ngModel像这样输入,考虑在 TS 中我制作了一个字典类型的数组

 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>

我有 onSelection 输出 this.students.marks,this.studentsCopy.marks

所以最初,让学生 1 有名字:“亚当”,标记:[1,2,3] 多选加载最初显示 1,2,3 突出显示,因为 ngModel 绑定完成,因为我为他选择标记:4然后对于 this.students.marks 它显示,name:"Adam",marks:[1,2,3,4] 这是完全可以接受的,但是为什么 this.studentsCopy.marks 也显示相同,ngModel 连接到原始数据而不是版权?

[编辑]:为此,

    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)

我得到 (2) [2, 1]

[2]文开的说,0:2 1:333

true 2 -> 不是数组而是数字

所以下次选择它说 push 不是一个函数,因为它被转换为一个数字?为什么 push 后的数组实例变成了数字?

标签: htmlangularangular-directive

解决方案


试试这样:

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

或者,

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

扩展运算符 ( ...) 可用于从另一个数组或对象初始化数组和对象,而无需引用(深度复制)


推荐阅读