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?
If you're already using Lodash, you can do this simple approach which includes both key and value:
In the typescript file, include:
and in the exported component, include:
Thanks for the pipe but i had to make some changes before i could use it in angular 2 RC5. Changed the Pipe import line and also added type of any to the keys array initialization.
You could create a custom pipe to return the list of key for each element. Something like that:
and use it like that:
Edit
You could also return an entry containing both key and value:
and use it like that:
There's a real nice library that does this among other nice pipes. It's called ngx-pipes.
For example, keys pipe returns keys for an object, and values pipe returns values for an object:
keys pipe
values pipe
No need to create your own custom pipe :)
From Angular 6.1 you can use the keyvalue pipe:
But it has the inconvenient that sorts the resulting list by the key value. If you need something neutral:
Don't forget to specify the pure:false pipe attribute. In this case, the pipe is invoked on each change-detection cycle, even if the input reference has not changed (so is the case when you add properties to an object).
You have to do it like this for now, i know not very efficient as you don't want to convert the object you receive from firebase.