我一直在挖掘,发现我可以使用以下内容在对象上使用* ngFor:
<div *ngFor="#obj of objs | ObjNgFor">...</div>
其中ObjNgFor
管道是:
@Pipe({ name: 'ObjNgFor', pure: false })
export class ObjNgFor implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => value[key]);
}
}
但是,当我有这样的对象时:
{
"propertyA":{
"description":"this is the propertyA",
"default":"sth"
},
"propertyB":{
"description":"this is the propertyB",
"default":"sth"
}
}
我不太确定如何提取'property'和'property',因此可以从* ngFor指令访问它。有任何想法吗?
UPDATE
我想要做的是呈现以下HTML:
<div *ngFor="#obj of objs | ObjNgFor" class="parameters-container">
<div class="parameter-desc">
{{SOMETHING}}:{{obj.description}}
</div>
</div>
什么东西等于propertyA
和propertyB
(这就是对象的结构)。所以,这会导致:
propertyA:this is the propertyA
propertyB:this is the propertyB
在6.1.0-beta.1中,KeyValuePipe
被引入https://github.com/angular/angular/pull/24319
<div *ngFor="let item of {'b': 1, 'a': 1} | keyvalue">
{{ item.key }} - {{ item.value }}
</div>
以前的版本
你可以尝试这样的事情
export class ObjNgFor implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => Object.assign({ key }, value[key]));
}
}
然后在你的模板上
<div *ngFor="let obj of objs | ObjNgFor">
{{obj.key}} - {{obj.description}}
</div>
或者不是创建管道并将对象传递给* ngFor,而是将Object.keys(MyObject)
传递给* ngFor。它返回与管道相同,但没有麻烦。
在TypeScript文件上:
let list = Object.keys(MyObject); // good old javascript on the rescue
在模板(html)上:
*ngFor="let item of list"
只需从管道返回键而不是值,然后使用键来访问值:
(let
而不是#
在beta.17)
@Pipe({ name: 'ObjNgFor', pure: false })
export class ObjNgFor implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value)//.map(key => value[key]);
}
}
@Component({
selector: 'my-app',
pipes: [ObjNgFor],
template: `
<h1>Hello</h1>
<div *ngFor="let key of objs | ObjNgFor">{{key}}:{{objs[key].description}}</div> `,
})
export class AppComponent {
objs = {
"propertyA":{
"description":"this is the propertyA",
"default":"sth"
},
"propertyB":{
"description":"this is the propertyB",
"default":"sth"
}
};
}
keys.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'keys' })
export class KeysPipe implements PipeTransform {
transform(obj: Object, args: any[] = null): any {
let array = [];
Object.keys(obj).forEach(key => {
array.push({
value: obj[key],
key: key
});
});
return array;
}
}
app.module.ts
import { KeysPipe } from './keys.pipe';
@NgModule({
declarations: [
...
KeysPipe
]
})
example.component.html
<elem *ngFor="let item of obj | keys" id="{{ item.key }}">
{{ item.value }}
</elem>