使用 *ngFor 访问对象的键和值 [英] access key and value of object using *ngFor
问题描述
我对如何在 angular2 中使用 *ngFor
迭代对象的 key
和 value
感到有些困惑目的.我知道在 angular 1.x 中有类似
ng-repeat="(key, value) in demo"
但我不知道如何在 angular2 中做同样的事情.我尝试过类似的东西,但没有成功:
<li *ngFor='#key of demo'>{{key}}</li>
演示 = {'key1': [{'key11':'value11'}, {'key12':'value12'}],'key2': [{'key21':'value21'}, {'key22':'value22'}],}
这是我尝试的 plnkr:http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview
如何使用*ngFor
动态获取key1
和key2
?在广泛搜索后,我发现了使用管道的想法,但我不知道如何去做.在 angular2 中是否有任何内置管道可以做同样的事情?
在 最新版本的 Angular (v6.1.0) 中,Angular Team 为与 相同的名称添加了新的内置管道code>keyvalue 管道可帮助您遍历 angular 包的 common
模块中的对象、映射和数组.例如 -
<div *ngFor="let item of testObject |键值">密钥:<b>{{item.key}}</b>和值:<b>{{item.value}}</b>
要保持原始顺序,请使用 keyvalue:onCompare
,
并在组件中定义回调:
//...从@angular/common"导入 {KeyValue};@成分(/* ... */)导出类 MyComponent {private onCompare(_left: KeyValue, _right: KeyValue): number {返回-1;}}
工作分叉示例
在这里查看更多有用的信息 -
- https://github.com/angular/angular/blob/master/CHANGELOG.md#features-3
- https://github.com/angular/angular/commit/2b49bf7
如果您使用的是 Angular v5 或更低版本,或者您想使用管道来实现,请遵循此答案
I am a bit confused about how to get the key
and value
of an object in angular2 while using *ngFor
for iterating over the object. I know in angular 1.x there is a syntax like
ng-repeat="(key, value) in demo"
but I don't know how to do the same in angular2. I have tried something similar, without success:
<ul>
<li *ngFor='#key of demo'>{{key}}</li>
</ul>
demo = {
'key1': [{'key11':'value11'}, {'key12':'value12'}],
'key2': [{'key21':'value21'}, {'key22':'value22'}],
}
Here is a plnkr with my attempt: http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview
How can I get key1
and key2
dynamically using *ngFor
? After searching extensively, I found the idea of using pipes but I don't know how to go about it.
Is there any inbuilt pipe for doing the same in angular2?
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 the common
module of angular package.
For example -
<div *ngFor="let item of testObject | keyvalue">
Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>
To keep original order, use keyvalue:onCompare
,
and in component define callback:
// ...
import {KeyValue} from '@angular/common';
@Component(/* ... */)
export class MyComponent {
private onCompare(_left: KeyValue<any, any>, _right: KeyValue<any, any>): number {
return -1;
}
}
Working Forked Example
check it out here for more useful information -
- https://github.com/angular/angular/blob/master/CHANGELOG.md#features-3
- https://github.com/angular/angular/commit/2b49bf7
If you are using Angular v5 or below or you want to achieve using pipe follow this answer
这篇关于使用 *ngFor 访问对象的键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!