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

查看:92
本文介绍了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.

这是一个令人眼花:乱的事情:

Here is a stackblitz:

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天全站免登陆