html - 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 后的数组实例变成了数字?
解决方案
试试这样:
this.studentsCopy = [...this.students]
或者,
this.studentsCopy = this.students.map(object => ({ ...object }))
扩展运算符 ( ...
) 可用于从另一个数组或对象初始化数组和对象,而无需引用(深度复制)
推荐阅读
- sql - 使用自动更新从现有父表创建相关表
- regex - 在正则表达式和 Openrefine 中匹配 /n 的文本
- html - 如何在 Firefox 上为 Windows 设计滚动条?
- c# - 如何限制(同步).net WebApi 请求的执行/请求时间?
- haskell - 偶数索引上列表的重复元素
- php - 地址验证限制超过 3 个特殊字符
- android - 原始 midi 值和字节 c++
- javascript - user.save 不会运行回调函数
- android - 无法解决:play-services-auth-base-license 版本 11.8.0
- sqlite - SQLite-Net 扩展 | 对同一实体的外键引用