How to iterate object keys using *ngFor?

后端 未结 5 613
温柔的废话
温柔的废话 2020-11-27 20:46

I\'ve been digging around, and found out that I can use the following to use *ngFor over an object:

 
...
5条回答
  •  被撕碎了的回忆
    2020-11-27 21:05

    keys.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({ name: 'keys' })
    export class KeysPipe implements PipeTransform {
        transform(obj: Object, args: any[] = null): any {
            let array = [];
            Object.keys(obj).forEach(key => {
                array.push({
                    value: obj[key],
                    key: key
                });
            });
            return array;
        }
    }
    

    app.module.ts

    import { KeysPipe } from './keys.pipe';
    
    @NgModule({
      declarations: [
        ...
        KeysPipe
      ]
    })
    

    example.component.html

    
        {{ item.value }}
    
    

提交回复
热议问题