【问题标题】:Angular 6 - Object Properties Updating without Setting themAngular 6 - 对象属性更新而不设置它们
【发布时间】:2019-03-10 02:26:08
【问题描述】:
【问题讨论】:
标签:
html
angular
typescript
angular6
【解决方案1】:
因为引用
this.tags = this.product.tags;
您可以执行以下操作(ES6):
this.tags = [...this.product.tags];
【解决方案2】:
使用此代码
this.initialProduct = this.product;
您将分配给this.initialProduct 的相同变量位于与this.product 相关的内存索引处。这是因为this.product 指向一个内存地址,而在前面的操作中,您只复制了内存地址。所以this.product 和this.initialProduct 指向同一个变量。
您需要创建另一个数组并将this.product 值复制到this.initialProduct(新数组)。
您可以通过多种方式做到这一点。例如:
// this.initialProduct = this.product;
this.initialProduct = {
tags: Array.from(this.product.tags)
}
或
// this.initialProduct = this.product;
this.initialProduct = {
tags: this.product.tags.concat()
}
或
// this.initialProduct = this.product;
this.initialProduct = {
tags: this.product.tags.slice()
}