I am hoping for a clear understanding of this situation.
To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below:
import {Directive, Input, OnChanges, SimpleChange, SimpleChanges} from "@angular/core";
import {NgForOf} from "@angular/common";
@Directive({
selector: "[ngFor][ngForIn]"
})
export class NgforinDirective<T> extends NgForOf<T> implements OnChanges {
@Input() public ngForIn: any;
public ngOnChanges(changes: SimpleChanges): void {
if (changes.ngForIn) {
if (this.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);
}
}
}
The current challenge is accessing the value of object[key] multiple times in the template. Currently, I am handling it using the following method (although not ideal):
<div *ngFor="let key in object">
{{object[key]}}
However, my goal is to be able to achieve something like this:
<div *ngFor="let key in object; let value = object[key]">
{{value}}
In my exploration, I have delved into the source code for ngForOf, where I observed the inclusion of local variables such as "index" and "odd".
I believe creating a local variable within the custom directive that can provide the value of the object[key] during iteration might offer a solution. However, I am uncertain about how to proceed with this approach or if there exists a simpler alternative that has eluded me.
Have you encountered a similar challenge and discovered a resolution?
Thank you!