Search code examples
angulartypescriptimmutable.js

Angular: how to iterate over Immutable js Map inside the template?


I want to use Immutable.js inside my angular application because i heard it improve the performance.

So i want to convert my code to use Immutable.js package.

So, my component has a regular typescript Map, which used inside the component's template. It iterated with *ngFor with keyValue pipe.

When i replace that map to Immutable.Map, the itertation wont work!!

So the question, how to iterate over Immutable.Map inside the template?

Thanks in ahead

Update: To reproduce the problem.

In app.component.ts:

import { Comoonent } from '@angular/core';
import { Map as immuMap } from 'immutable' ;

@Component({
  selector: 'app-map', 
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'] 
}) 
export class AppComponent {
  myMap = immuMap({ a: 1, b: 2, c:3});
}

In app.component.html :

<div *ngFor="let item of myMap | keyvalue">
  <span>{{ item.key }} : {{ item.value }}</span>
</div>

When myMap was a simple typescript Map, it worked. The code above is after refactor to Immutable.js Map. And now the ngFor wont produce same result as was before....

The result of above code is:

__altered : false 
__hash : 
__ownerID: 
_root : [object Object] 
size : 3

Solution

  • Since immutable collections are already iterables, you can just remove the keyvalue pipe. ngFor can treat immutable.js Map exactly like a native javascript Map.

    Entries of Map's iterator are arrays in format [key, value]

    const imMap = Immutable.Map({ a: 1, b: 2, c:3});
    for(entry of imMap ) {
      console.log('entry', entry[0], 'is', entry[1]);
    }
    
    const nativeMap = new window.Map([['a',1], ['b',2], ['c':3]]);
    for(entry of nativeMap ) {
      console.log('entry', entry[0], 'is', entry[1]);
    }
    
    // both loops will output:
    // entry a is 1
    // entry b is 2
    // entry c is 3