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

4 Answers

0
Community On Best Solutions

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

0
abd995 On

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

0
Richard Fox On

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

0
onik On

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

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