简体   繁体   中英

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);

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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