2

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.

sP_
  • 1,738
  • 2
  • 15
  • 29
Karthigeyan Vellasamy
  • 2,038
  • 6
  • 33
  • 50

2 Answers2

1

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

{{ priority.get(item.priority) }}
David Anthony Acosta
  • 4,766
  • 1
  • 19
  • 19
1

write a pipe like this:

import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
  name: 'mapValue'
})
export class MapValuePipe  implements PipeTransform{
  transform<K,V>(map: Map<K,V>,key: K): V {
    return map.get(key);
  }
}

if you want to get value of a key in tempate:

{{aMap |mapValue:'a key'}}

if you want use ngFor to iterate keys or values,you can write a pipe like above.

Yuxing Xie
  • 31
  • 7