访问密钥,并使用对象的值* ngFor [英] access key and value of object using *ngFor
问题描述
有点困惑如何获得键和对象的值
在angular2而USNG * ngFor迭代结束对象。我知道在角1.x中有类似的语法
Bit confused about how to get Key and Value
of object in angular2 while usng *ngFor for iteration over object. i know in angular 1.x there is syntax like
ng-repeat="(key, value) in demo"
但在angular2我不知道我累了一样,但我以前不得到成功。我曾尝试低于code,但我以前不运行,请告诉我,我做错了。
but in angular2 i don't know i tired the same but did't get successful. i have tried the below code but did'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'}],
}
这里是哪里plnkr我曾尝试相同的:
http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=$p$pview一>
我想获得键1和键2
动态使用* ngFor。怎么弄呢?
我搜索发现了很多用管,但怎么用我不知道的想法。
有没有在做angular2任何相同inbuild管?
i want to get key1 and key2
dynamically using *ngFor. how to get it ?
i searched alot found idea of using pipe but how to use i dont know.
is there any inbuild pipe for doing same in angular2 ?
推荐答案
您可以创建一个自定义管道返回键列表中的每个元素。
这样的事情:
You could create a custom pipe to return the list of key for each element. Something like that:
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push(key);
}
return keys;
}
}
和使用这样的:
<tr *ngFor="#c of content">
<td *ngFor="#key of c | keys">{{key}}: {{c[key]}}</td>
</tr>
修改
您也可以返回一个包含入口密钥和值:
You could also return an entry containing both key and value:
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]);
}
return keys;
}
}
和使用这样的:
<span *ngFor="#entry of content">
Key: {{entry.key}}, value: {{entry.value}}
</span>
这篇关于访问密钥,并使用对象的值* ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!