问题
I have an editor where the user can edit a product. I save an instance of the product in ngOnInit
under initialProduct
to make it possible to reset the edits.
Unfortunately, I have a weird issue: When adding a new tag the properties of the initialProduct
changes without setting them.
Here is a stackblitz:
https://stackblitz.com/edit/angular-yxrh2d?file=src%2Fapp%2Fapp.component.ts
回答1:
With this code
this.initialProduct = this.product;
you are assigning to this.initialProduct
the same variable positioned at the memory index related by this.product
. This because this.product
points to a memory address and with the previous operation you are copying only the memory address. So this.product
and this.initialProduct
point to the same variable.
You need to create another array and to copy this.product
values into this.initialProduct
(new array).
You can do this by various ways. For example:
// this.initialProduct = this.product;
this.initialProduct = {
tags: Array.from(this.product.tags)
}
or
// this.initialProduct = this.product;
this.initialProduct = {
tags: this.product.tags.concat()
}
or
// this.initialProduct = this.product;
this.initialProduct = {
tags: this.product.tags.slice()
}
回答2:
because of references
this.tags = this.product.tags;
You can do the following (ES6):
this.tags = [...this.product.tags];
来源:https://stackoverflow.com/questions/52651051/angular-6-object-properties-updating-without-setting-them