Search code examples
angularangular2-changedetection

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. So i need that @Input CurrentHero will have every time new reference, which not happend.

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.


Solution

  • 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.

    I don't know how you change values of heroes individual properties, but if you go like this

    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. Spreading it like {...this.heroes} will persist old references to every individual object in that array.