Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - changing the variable but doesn't refresh the view

I have an array variable, which contains objects, just like this:

[{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...]

I have a view, which prints out the list of the products, like this:

<div *ngFor="let item of items">
   {{item.name}} - {{item.price}}
</div>

This is just an example but the 'model' of the problem is the same:

If I change the 'items' array from the code (for example because an external event occured) the variable value is changes, but the view won't refreshed :(.

How can I make this work?

Edit:

changeArray() includes only one line:

changeArray(items) : void{ this.items = items; }

Maybe the problem is that, I call this method of A, from an another component? So, in component 'B', I have a line just like this:

a.changeArray(items);

like image 748
Prometheus Avatar asked Sep 24 '18 14:09

Prometheus


2 Answers

One way to force refresh the list is to use the spread operator ...

So after you have updated your (say) items property in your component, do this,

// after items are updated logic, and assuming it is an array,
this.items = [...this.items];

this should refresh your list.

If you provide your entire code to replicate the problem, this force change approach may be fine tuned.

UPDATE:

Based on your comments,

update the changeArray() to this,

changeArray(items) : void{
  this.items = [...items];
}

UPDATE2:

If the above doesn't work, try this too,

in the component where changeArray() is defined, add this to the constructor and import ChangeDetectorRef as well,

import { ChangeDetectorRef } from '@angular/core';

constructor(cRef: ChangeDetectorRef) {}

changeArray(items) : void{
  this.items = [...items];
  this.cRef.detectChanges();
}

Hope it works.

like image 67
amal Avatar answered Nov 08 '22 06:11

amal


Angular expects arrays to be immutable. You cannot alter the contents of the array, but need to create a new one (change the reference).

As an example use concat which returns a new array instead of push to add elements.

like image 6
kubal5003 Avatar answered Nov 08 '22 05:11

kubal5003