Iterate over object in Angular

前端 未结 17 1561
攒了一身酷
攒了一身酷 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:38

    Angular 2.x && Angular 4.x do not support this out of the box

    You can use this two pipes to iterate either by key or by value.

    Keys pipe:

    import {Pipe, PipeTransform} from '@angular/core'
    
    @Pipe({
      name: 'keys',
      pure: false
    })
    export class KeysPipe implements PipeTransform {
      transform(value: any, args: any[] = null): any {
        return Object.keys(value)
      }
    }
    

    Values pipe:

    import {Pipe, PipeTransform} from '@angular/core'
    
    @Pipe({
      name: 'values',
      pure: false
    })
    export class ValuesPipe implements PipeTransform {
      transform(value: any, args: any[] = null): any {
        return Object.keys(value).map(key => value[key])
      }
    }
    

    How to use:

    let data = {key1: 'value1', key2: 'value2'}
    
    

提交回复
热议问题