suchen

Heim  >  Fragen und Antworten  >  Hauptteil

angular.js - angular2中如何对ngfor的遍历的项目元素再进行循环渲染?

我拿到的数据:

    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}
    ];
    
    

我的template:

<p>

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


我想对item里的key再进行遍历,拿到对应的value循环渲染到<td>元素中.我的template该怎么写?

...

阿神阿神2745 Tage vor566

Antworte allen(2)Ich werde antworten

  • 伊谢尔伦

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

    ng2这点让我非常不爽,居然不能天然遍历Object,我们只能自己写了,为了不让你困惑,我用最简单的方式来玩,

    首先是template部分:

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

    下面是Component逻辑部分:

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

    方法肯定可以用,自己玩玩看吧

    Antwort
    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}
        ];
    }

    Antwort
    0
  • StornierenAntwort