I am trying to do some things in Angular 2 Alpha 28, and am having an issue with dictionaries and NgFor.
I have an interface in TypeScript looking like this:
interface Dictionary {
[ index: string ]: string
}
In JavaScript this will translate to an object that with data might look like this:
myDict={'key1':'value1','key2':'value2'}
I want to iterate over this and tried this:
<div *ngFor="(#key, #value) of myDict">{{key}}:{{value}}</div>
But to no avail, none of the below worked either:
<div *ngFor="#value of myDict">{{value}}</div>
<div *ngFor="#value of myDict #key=index">{{key}}:{{value}}</div>
In all cases I get errors like "Unexpected token" or "Cannot find 'iterableDiff' pipe supporting object"
What am I missing here? Is this not possible anymore? (The first syntax works in Angular 1.x) or is the syntax different for iterating over an object?
In addition to @obscur's answer, here is an example of how you can access both the
key
andvalue
from the @View.Pipe:
View:
So if the object were to look like:
The generated outcome would be:
First name: Daario
Last Name: Naharis
First name: Victarion
Last Name: Greyjoy
First name: Quentyn
Last Name: Ball
Adding to SimonHawesome's excellent answer. I've made an succinct version which utilizes some of the new typescript features. I realize that SimonHawesome's version is intentionally verbose as to explain the underlying details. I've also added an early-out check so that the pipe works for falsy values. E.g., if the map is
null
.Note that using a iterator transform (as done here) can be more efficient since we do not need to allocate memory for a temporary array (as done in some of the other answers).
I had a similar issue, built something for objects and Maps.
Interfaces in TypeScript are a dev time construct (purely for tooling ... 0 runtime impact). You should write the same TypeScript as your JavaScript.
Here's a variation on some of the above answers that supports multiple transforms (keyval, key, value):
Usage
Updated : Angular is now providing the pipe for lopping through the json Object via
keyvalue
:WORKING DEMO , and for more detail Read
Previously (For Older Version) : Till now the best / shortest answer I found is ( Without any Pipe Filter or Custom function from Component Side )
WORKING DEMO