Angular2: loop typescript dictionary in html component

Viewed 5011

I'm developing an Angular 2 application and I want to loop a Typescript dictionary to show its data.

The interface I want to show is:

export interface IProductionOrderDetail {
    productionOrderName: string;
    productCode: string;
    batches: IBatch[];
    levels: IAggLevel[];
    variableData: IVarData[];
    codeStatistics: ICodeStatistics;
}

export interface ICodeStatistics {
    [index: number]: {
        commissionedCodes: number;
        decommissionedCodes: number;
        aggregatedCodes: number;
    }
}

I know that I can do this in TypeScript to loop the dictionary:

for (let key in myDictionary) {
    let value = myDictionary[key];
    // Use `key` and `value`
}

So, I have decided to use it in the same way in a html component:

<div class="row" *ngFor="let key in prodetail.codeStatistics">
    <div class="col-md-1">{{queryLevelName(key)}}</div>
    <div class="col-md-1">{{prodetail.codeStatistics[key].commissionedCodes}}</div>
    <div class="col-md-1">{{prodetail.codeStatistics[key].decommissionedCodes}}</div>
    <div class="col-md-1">{{prodetail.codeStatistics[key].aggregatedCodes}}</div>
</div>

But it seems that there is something wrong with the in in *ngFor="let key in prodetail.codeStatistics" because I get the following error:

Can't bind to 'ngForIn' since it isn't a known property of 'div'. (" ]*ngFor="let key in prodetail.codeStatistics">

How can I loop over the dictionary?a

1 Answers

In latest version of Angular (6.0.0+) : So great to find the best solution from Angular itself provides pipe to loop through JSON , and its keyvalue

<div *ngFor='let item of jsonObj | keyvalue'>
   Key: {{item.key}}

    <div *ngFor='let obj of item.value'>
        {{ obj.title }}
        {{ obj.desc }}
    </div>

</div>

WORKIGN DEMO


Previously :

As angular doesn't support jsonObject looping from template side and there is no ngForIn directive yet ,

You can loop through the data only if its array with *ngForOf , but if you want to loop through json or dictionary You can do it like

Component side :

objectKeys = Object.keys;

Template side :

<div class="row" *ngFor="let key of objectKeys(prodetail.codeStatistics)">
    <div class="col-md-1">{{queryLevelName(key)}}</div>
    <div class="col-md-1">{{prodetail.codeStatistics[key].commissionedCodes}}</div>
    <div class="col-md-1">{{prodetail.codeStatistics[key].decommissionedCodes}}</div>
    <div class="col-md-1">{{prodetail.codeStatistics[key].aggregatedCodes}}</div>
</div>

WORKING DEMO

Related