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);
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);
2 Answers
Reset to default 10One 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.
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.
items
array is modified in your code. – Martin Parenteau Commented Sep 24, 2018 at 14:41changeArray()
. – Martin Parenteau Commented Sep 24, 2018 at 14:42changeArray
? – Ruben Vermeulen Commented Sep 24, 2018 at 15:52