Can ngForIn be used in angular 4?
The easiest approach would be to turn your object into an array using Object.values()
and Object.keys()
. Check out this plunker for an example.
If you want access to the keys as well as the value you can include an index in your *ngFor
.
Template:
<ul>
<li *ngFor="let item of array; let index = index;">
<b>{{keys[index]}}</b> value: {{item}}, index: {{index}}
</li>
</ul>
Component TypeScript:
export class App {
obj = {a: 1, b: 2}
array = [];
keys = [];
constructor() {
}
ngOnInit() {
this.array = Object.values(this.obj);
this.keys = Object.keys(this.obj);
}
}
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