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?
Elaboration of @Thierry's answer with example.
There is no inbuilt pipe or method to get
key and value
from the *ngFor loop. so we have to create custom pipe for the same. as thierry said here is the answer with code.** The pipe class implements the PipeTransform interface's transform method that takes an input value and an optional array of parameter strings and returns the transformed value.
** The transform method is essential to a pipe. The PipeTransform interface defines that method and guides both tooling and the compiler. It is optional; Angular looks for and executes the transform method regardless. for more info regards pipe refer here
and HTML part is:
Working Plnkr http://plnkr.co/edit/50LlK0k6OnMnkc2kNHM2?p=preview
update to RC
as suggested by user6123723(thanks) in comment here is update.
None of the answers here worked for me out of the box, here is what worked for me:
Create
pipes/keys.ts
with contents:Add to
app.module.ts
(Your main module):and then add to your module declarations array something like this:
Then in your view template you can use something like this:
Here is a good reference I found if you want to read more.
Here is the simple solution
You can use typescript iterators for this