1
votes

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....

BTW, the result of above code is: __altered : false __hash : __ownerID: _root : [object Object] size : 3

1
Please help responders reproduce your problem by adding code and describe the issue ("won't work" is not a problem description) (How to ask a good question). All immutable.js collections support the iterable pattern, so this is likely a problem specific to your code. - dube
@dube Thank you for your comment! "Iterating in Angular..." doesnt answer my question. Because he use List and i use Map. I updated the question. - Baruch Levin

1 Answers

2
votes

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