Iterate over object in Angular

2019-01-01 02:02发布

I am trying to do some things in Angular 2 Alpha 28, and am having an issue with dictionaries and NgFor.

I have an interface in TypeScript looking like this:

interface Dictionary {
    [ index: string ]: string
}

In JavaScript this will translate to an object that with data might look like this:

myDict={'key1':'value1','key2':'value2'}

I want to iterate over this and tried this:

<div *ngFor="(#key, #value) of myDict">{{key}}:{{value}}</div>

But to no avail, none of the below worked either:

<div *ngFor="#value of myDict">{{value}}</div>
<div *ngFor="#value of myDict #key=index">{{key}}:{{value}}</div>

In all cases I get errors like "Unexpected token" or "Cannot find 'iterableDiff' pipe supporting object"

What am I missing here? Is this not possible anymore? (The first syntax works in Angular 1.x) or is the syntax different for iterating over an object?

标签: angular
15条回答
ら面具成の殇う
2楼-- · 2019-01-01 02:55

If you have es6-shim or your tsconfig.json target es6, you could use ES6 Map to make it.

var myDict = new Map();
myDict.set('key1','value1');
myDict.set('key2','value2');

<div *ngFor="let keyVal of myDict.entries()">
    key:{{keyVal[0]}}, val:{{keyVal[1]}}
</div>
查看更多
忆尘夕之涩
3楼-- · 2019-01-01 02:56

If someone is wondering how to work with multidimensional object, here is the solution.

lets assume we have following object in service

getChallenges() {
    var objects = {};
    objects['0'] = { 
        title: 'Angular2', 
        description : "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."
    };

    objects['1'] = { 
        title: 'AngularJS', 
        description : "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
    };

    objects['2'] = { 
        title: 'Bootstrap',
        description : "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
    };
    return objects;
}

in component add following function

challenges;

constructor(testService : TestService){
    this.challenges = testService.getChallenges();
}
keys() : Array<string> {
    return Object.keys(this.challenges);
}

finally in view do following

<div *ngFor="#key of keys();">
    <h4 class="heading">{{challenges[key].title}}</h4>
    <p class="description">{{challenges[key].description}}</p>
</div>
查看更多
时光乱了年华
4楼-- · 2019-01-01 02:56

Define the MapValuesPipe and implement PipeTransform:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'mapValuesPipe'})
export class MapValuesPipe implements PipeTransform {
    transform(value: any, args?: any[]): Object[] {
        let mArray: 
        value.forEach((key, val) => {
            mArray.push({
                mKey: key,
                mValue: val
            });
        });

        return mArray;
    }
}

Add your pipe in your pipes module. This is important if you need to use the same pipe in more than one components:

@NgModule({
  imports: [
    CommonModule
  ],
  exports: [
    ...
    MapValuesPipe
  ],
  declarations: [..., MapValuesPipe, ...]
})
export class PipesAggrModule {}

Then simply use the pipe in your html with *ngFor:

<tr *ngFor="let attribute of mMap | mapValuesPipe">

Remember, you will need to declare your PipesModule in the component where you want to use the pipe:

@NgModule({
  imports: [
    CommonModule,
    PipesAggrModule
  ],
...
}
export class MyModule {}
查看更多
登录 后发表回答