andy
andy

Reputation: 129

How can i re-render ngFor when data doesn't change?

Overview:

I have a list that binds two arrays together with an ngfor using pipes. i bind the arrays on a typeID.

One array lists all the available types and the other holds the selected types along with an extra option. Note The arrays only share 2 properties, name and id

Problem:

Because my ngFor is bound to the first array when data changes in the second array nothing is updated so at the minute i have to recall my http method which grabs the exact same data just to update the list.

I need a way to force rerender without calling my api everytime something in the second array changes

StackBlitz:

https://stackblitz.com/edit/angular-nxkwaf

Upvotes: 0

Views: 4740

Answers (4)

andy
andy

Reputation: 129

Using a tweaked version of onik's solution i managed to solve this with less lines of code

Solution

this.secondary = this.secondary.concat({ primaryID: primary.primaryID, name: primary.name, isChecked: false });

Stackblitz

https://stackblitz.com/edit/angular-rydedr

Upvotes: 1

onik
onik

Reputation: 1631

you can set for new reference on this array and it will rerender,

this.secondary = [...this.secondary];

Upvotes: 0

abd995
abd995

Reputation: 1839

You can use ngIf and a setTimeout to make the ngFor re render. Call this.reload() instead of this.getPrimary()

reload() {
  this.show = false;
  setTimeout(() => this.show = true);
}

Wrap the ngFor inside a ngIf

<ul class="list list-a" *ngIf="show">
   <li *ngFor="let p of primary;">

Plunker : https://stackblitz.com/edit/angular-geuesx

Upvotes: 1

Tobias Fuchs
Tobias Fuchs

Reputation: 938

you can import the ChangeDetectorRef from the angular core and trigger markForCheck. This is probably not the optimal way, but it should re-render the component in your case

Upvotes: 0

Related Questions