I am trying to view JavaScript Map type in Angular template and value is coming empty always even when I intialise it with some default value.
Angular Component
export class AppComponent implements OnInit {
public myJsMap:Map<string,string> = new Map<string,string>([['hello','hello']]);
ngOnInit(): void {
this.myJsMap.set('Hello2', 'hellow2')
}
}
Angular Template
My Template Value : {{myJsMap | json}}
Tried to console log Map value on the component and it prints correctly on component side but when tried to view same value on template side it is showing empty object always. Anything we need to do on template side to view this value?
2
Answers
You cannot use Angular
json
pipe against an ES6 Map. If you checkjson
pipe source, you will find that it makes use ofJSON.stringify()
method, which results for{}
for any ES6 MapYou can either iterate over your map entries in your component HTML file using
NgFor
directive andkeyvalue
pipe like belowOR build your own pipe that can transform it
and use it in your component HTML file like below