Iterate over object in Angular

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

    In addition to @obscur's answer, here is an example of how you can access both the key and value from the @View.

    Pipe:

    @Pipe({
       name: 'keyValueFilter'
    })
    
    export class keyValueFilterPipe {
        transform(value: any, args: any[] = null): any {
    
            return Object.keys(value).map(function(key) {
                let pair = {};
                let k = 'key';
                let v = 'value'
    
    
                pair[k] = key;
                pair[v] = value[key];
    
                return pair;
            });
        }
    
    }
    

    View:

  • First Name: {{u.key}}
    Last Name: {{u.value}}
  • So if the object were to look like:

    myObject = {
        Daario: Naharis,
        Victarion: Greyjoy,
        Quentyn: Ball
    }
    

    The generated outcome would be:

    First name: Daario
    Last Name: Naharis

    First name: Victarion
    Last Name: Greyjoy

    First name: Quentyn
    Last Name: Ball

提交回复
热议问题