Search code examples
angularangular2-template

Angular 2 Access value from map using known key inside template


How to get value from map if I know the key and get it like map[key] and tried myMap.get(key).

Might be duplicate of access key and value of object using *ngFor and https://stackoverflow.com/a/45233924/1225526

But a small change in my scenario, I know the key, I have map like :

priority: Map<number, string> = new Map<number, string>();

ngOnInit() {
    this.priority.set(1, Packages.PRIORITY_TYPES.highest);
    this.priority.set(2, Packages.PRIORITY_TYPES.high);
    this.priority.set(3, Packages.PRIORITY_TYPES.medium);
    this.priority.set(4, Packages.PRIORITY_TYPES.low);
    this.priority.set(5, Packages.PRIORITY_TYPES.info);
}

I am trying to get the value in my template like {{priority[item.priority]}} here item.priority has the key value

<span [ngClass]="'baseline-text-'+ priority.get(item.priority)">
  {{priority[item.priority]}}</span>    <-- looks like wrong syntax i am not getting the value in my html

Any help would be great.


Solution

  • the same way you got it in your span class, you must do:

    {{ priority.get(item.priority) }}