[Fixed] Angular, how to track Map <string, any>() modification?

Issue

I’m using Angular 9 and i would like to track when my Map<string, any>() is modified.

Context :

I want to display in a vertical scrolling list the values of my Map using the angular cdk scrolling.

So, cause of cdkVirtualFor data type limitation, i need to create a simple array in order to display my Map data.

So i created it with Array.from(myMap.values());

let myMap = new Map<string, any>(); // My main Map
let myArrayToMyScrollingList = Array.from(myMap.values()); // My array to display feed by My main Map values

So in my HTML Component file, i have :

<cdk-virtual-scroll-viewport [itemSize]="itemSize" [minBufferPx]="itemLength" [maxBufferPx]="itemLength">
     <div *cdkVirtualFor="let item of myArrayToMyScrollingList">
          {{ item  }}
     </div>
</cdk-virtual-scroll-viewport>

So it’s works.

However when myMap is updated, myArrayToMyScrollingList don’t apply the changement.

How to detect a Map<string, any>() value modification in order to tell my myArrayToMyScrollingList he has to update his value ?

What i’ve test:

  • changeDetection: ChangeDetectionStrategy.OnPush or ChangeDetectionStrategy.Default with @Input() by passing myMap as parameter. But no change detection is found when myMap has a value modification.

Thanks for help,
Regards

Solution

I sometimes use something like this (generic way):

TS

private myMap = new Map<number, YourTypeHere>();
private myValues$$ = new ReplaySubject<YourTypeHere[]>(1);
public myValues$ = this.myValues$$.asObservable()


public updateMap(key,value) {
   this.myMap.set(key, value);
   this.updateMyValues();
}

private updateMyValues() {
   this.myValues.next(Array.from(this.myMap.values()));
}
 

HTML

<div *ngFor="let item of myValues$ async">
   {{item.name}}
</div>

Leave a Reply

(*) Required, Your email will not be published