search

Home  >  Q&A  >  body text

angular.js - How to re-render the item elements traversed by ngfor in a loop in angular2?

The data I got:

    var items=[
        { "version": "1", "theme": "Windstorm" ,"age":20},
        { "version": "2", "theme": "Bombasto","age":21},
        { "version": "3", "theme": "Magneta" ,"age":22},
        { "version": "4", "theme": "Tornado" ,"age":23}
    ];
    
    

My template:

<p>

<p>
      <tr *ngFor="let item of items">
        <td *ngFor="怎么写">怎么写</td>
      </tr>
</p>
</p>


I want to traverse the keys in the item, get the corresponding value, and render it into the <td> element in a loop. How should I write my template?

...

阿神阿神2846 days ago612

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-15 17:04:57

    ng2这点让我非常不爽,居然不能天然遍历Object, we can only write it ourselves, in order not to confuse you, I use the simplest way to play,

    First is the template part:

    <tr *ngFor="let item of items">
        <td *ngFor="let key of getKeys(item)">
            {{ key }} = {{ item[key]  }}
        </td>
    </tr>

    The following is the Componentlogical part:

    @Component({
      selector: 'test',
      templateUrl: 'template.html',
      styleUrls:  ['style.css']
    })
    export class ItemsComponent {
    
        //关键就是这个getKeys方法,得自己写,真他妈的
        getKeys(item){
            return Object.keys(item);
        }
    }

    The method definitely works, just try it and see for yourself

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-15 17:04:57

    keys.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({name: 'keys'})
    export class KeysPipe implements PipeTransform {
        transform(value: any, args: string[]): string[] {
            if (typeof(value) !== 'object')
                throw 'keysPipe value must be object';
    
            return Object.keys(value);
        }
    }

    app.component.ts

    import { Component } from '@angular/core';
    import { KeysPipe } from './keys.pipe';
    
    @Component({
        selector: 'app',
        template: `
            <table>
              <tr *ngFor="let item of items">
                <td *ngFor="let key of item | keys">{{key}} - {{item[key]}}</td>
              </tr>
            </table>
        `,
        pipes: [KeysPipe]
    })
    export class AppComponent {
        items = [
            {'version': '1', 'theme': 'Windstorm', 'age': 20},
            {'version': '2', 'theme': 'Bombasto', 'age': 21},
            {'version': '3', 'theme': 'Magneta', 'age': 22},
            {'version': '4', 'theme': 'Tornado', 'age': 23}
        ];
    }

    reply
    0
  • Cancelreply