angular - 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。
我在哪里犯错?
解决方案
你的数组被克隆了,你的数组中的对象不是。如果它是一个浅对象,您可以执行以下操作:
ngOnInit() {
this.businessArray = [...this.contactInformation.business].map((data) => ({ ...data }));
}
还有很多图书馆可以帮助你解决这个问题
推荐阅读
- spring - 导入org.springframework 无法解决
- r-markdown - 抑制 RMarkdown 中的消息 - 不起作用
- c# - 在多个项目中共享 wwwroot
- android - Crashlytics 不会使用 apk-splits 上传映射文件
- sql - 提取超过一个月没有数据输入的工作区
- c++ - c++ 11 typeid of string and sizeof nullptr
- kubernetes - Hazelcast 无法在 Kubernetes 中启动
- c# - 我们可以使用 Web API 发送内存流对象吗?
- c++ - 我对 substr 函数有问题(C++)
- python - TypeError: unhashable type: 'list' using add edge from networkx