Angular 6 - 更新对象属性而不设置它们 [英] Angular 6 - Object Properties Updating without Setting them

查看:23
本文介绍了Angular 6 - 更新对象属性而不设置它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个编辑器,用户可以在其中编辑产品.我将产品的一个实例保存在 initialProduct 下的 ngOnInit 中,以便可以重置编辑.

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.

不幸的是,我遇到了一个奇怪的问题:当添加一个新标签时,initialProduct 的属性会发生变化而没有设置它们.

Unfortunately, I have a weird issue: When adding a new tag the properties of the initialProduct changes without setting them.

这是一个堆栈闪电战:

https://stackblitz.com/edit/angular-yxrh2d?file=src%2Fapp%2Fapp.component.ts

推荐答案

使用此代码

this.initialProduct = this.product;

您正在为 this.initialProduct 分配位于与 this.product 相关的内存索引处的相同变量.这是因为 this.product 指向一个内存地址,并且在前面的操作中你只复制了内存地址.所以 this.productthis.initialProduct 指向同一个变量.

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.

您需要创建另一个数组并将this.product 值复制到this.initialProduct(新数组)中.

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)
    }

    // this.initialProduct = this.product;
    this.initialProduct = {
      tags: this.product.tags.concat()
    }

    // this.initialProduct = this.product;
    this.initialProduct = {
      tags: this.product.tags.slice()
    }

这篇关于Angular 6 - 更新对象属性而不设置它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆