ngForIn可以在角度4中使用吗? [英] Can ngForIn be used in angular 4?
问题描述
我试图使用*ngFor
但使用in
遍历对象的属性.当我尝试这样做
I am trying to iterate over the properties of an object using *ngFor
but using in
. When I try to do this
@Controller({
selector: 'sample-controller',
template: `
<ul>
<li *ngFor="let i in obj">
<b>{{i}}</b>: {{obj[i]}}
</li>
</ul>`
})
class SampleController {
obj = {a: 1, b: 2}
}
我收到错误消息:
由于它不是'li'的已知属性,因此无法绑定到'ngForIn'.
Can't bind to 'ngForIn' since it isn't a known property of 'li'.
我已经在@NgModule
的imports
部分中包含了FormsModule
和BrowserModule
.
I have included FormsModule
and BrowserModule
in the imports
section of the @NgModule
for this component.
是否可以在li
上使用ngForIn
,如果没有,这是惯用的选择吗?
Is it possible to use ngForIn
on li
and if not is there an idiomatic alternative?
推荐答案
正如注释中提到的AJT_82一样,您可以为此目的创建特殊指令.它将基于NgForOf<T>
指令:
As AJT_82 mentioned in comment you can create special directive for such purposes. It will be based on NgForOf<T>
directive:
interface NgForInChanges extends SimpleChanges {
ngForIn?: SimpleChange;
ngForOf?: SimpleChange;
}
@Directive({
selector: '[ngFor][ngForIn]'
})
export class NgForIn<T> extends NgForOf<T> implements OnChanges {
@Input() ngForIn: any;
ngOnChanges(changes: NgForInChanges): void {
if (changes.ngForIn) {
this.ngForOf = Object.keys(this.ngForIn) as Array<any>;
const change = changes.ngForIn;
const currentValue = Object.keys(change.currentValue);
const previousValue = change.previousValue ?
Object.keys(change.previousValue) : undefined;
changes.ngForOf = new SimpleChange(previousValue, currentValue, change.firstChange);
super.ngOnChanges(changes);
}
}
}
Plunker Example
这篇关于ngForIn可以在角度4中使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!