Iterate over object in Angular

前端 未结 17 1318
攒了一身酷
攒了一身酷 2020-11-22 12:19

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:

17条回答
  •  囚心锁ツ
    2020-11-22 12:45

    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:

    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 {}
    

提交回复
热议问题