简体   繁体   English

在 angular 中,是否可以在模板内部创建副本 object?

[英]In angular, is it possible inside the template to create a copy object?

I have a code similiar to this:我有一个与此类似的代码:

<ng-container *ngFor="let hero of heroes">
   <my-comp [CurrentHero]="hero"></mycomp>
</ng-container>

Now, in my application heroes array never change reference, just update his own values.现在,在我的应用程序中的英雄数组永远不会改变引用,只是更新他自己的值。

So, also "hero" never has a new reference.所以,“英雄”也从来没有新的指称。

But, i want that the component "my-comp" to be with OnPush strategy.但是,我希望组件“my-comp”与 OnPush 策略一起使用。 So i need that @Input CurrentHero will have every time new reference, which not happend.所以我需要@Input CurrentHero 每次都会有新的参考,这没有发生。

Is there a possibility to copy inside the tenplate the hero to be a new refernce?是否有可能在天板内复制英雄作为新的参考?

Something like:就像是:

<my-comp [CurrentHero]="{...hero}" ></my-comp>

Thanks in advance.提前致谢。

Well that would be an anti-pattern if you are going with immutability.好吧,如果您要使用不变性,那将是一种反模式。

What you should do is that when you are changing value of heroes, you should always return new object to heroes variable.您应该做的是,当您更改英雄的值时,您应该始终将新的 object 返回到heroes变量。

I don't know how you change values of heroes individual properties, but if you go like this我不知道你如何改变heroes个人属性的值,但如果你像这样 go

changingHeroes() {
  let newHeroes = JSON.parse(JSON.stringify(this.heroes));

  newHeroes[0].something = 123;

  this.heroes = newHeroes;
}

Notice JSON.parse(JSON.stringify(this.heroes)) this is to do a deep copy of the object.注意JSON.parse(JSON.stringify(this.heroes))这是对 object 进行深拷贝。 Spreading it like {...this.heroes} will persist old references to every individual object in that array.{...this.heroes}一样传播它将保留对该数组中每个 object 的旧引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM