Bit confused about how to get Key and Value
of an object in angular2 while using *ngFor for iteration over the object. I know in angular 1.x there is syntax like
ng-repeat="(key, value) in demo"
but in angular2 I don't know I tried the same but didn't get successful. I have tried the below code but didn't run please tell me where I am doing wrong.
<ul>
<li *ngFor='#key of demo'>{{key}}</li>
</ul>
demo = {
'key1': [{'key11':'value11'}, {'key12':'value12'}],
'key2': [{'key21':'value21'}, {'key22':'value22'}],
}
here is plnkr where I have tried the same : http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview
I want to get key1
and key2
dynamically using *ngFor. How to get it?
I searched a lot found the idea of using pipe but how to use I don't know.
is there any inbuild pipe for doing same in angular2?
Update
In 6.1.0-beta.1 KeyValuePipe was introduced https://github.com/angular/angular/pull/24319
Plunker Example
Previous version
Another approach is to create
NgForIn
directive that will be used like:Plunker Example
ngforin.directive.ts
change demo type to array or iterate over your object and push to another array
and from html:
As in latest release of Angular (v6.1.0) , Angular Team has added new built in pipe for the same named as
keyvalue
pipe to help you iterate through objects, maps, and arrays, in thecommon
module of angular package. For example -Working Forked Example
check it out here for more useful information -
If you are using Angular v5 or below or you want to achieve using pipe follow this answer
@Marton had an important objection to the accepted answer on the grounds that the pipe creates a new collection on each change detection. I would instead create an HtmlService which provides a range of utility functions which the view can use as follows:
Have
Object.keys
accessible in the template and use it in*ngFor
.I think Object.keys is the best solution to this problem. For anyone that comes across this answer and is trying to find out why Object.keys is giving them ['0', '1'] instead of ['key1', 'key2'], a cautionary tale - beware the difference between "of" and "in":
I was already using Object.keys, something similar to this:
However, instead of
I had inadvertently wrote
which "worked" perfectly fine without any error and returned
That cost me about 2 hours googling and cursing..
(slaps forehead)