How to use ngFor to display the data as matrix

前端 未结 2 1125
粉色の甜心
粉色の甜心 2021-01-03 08:11
  • Edited to put more description *

I am new on Angular2. I have use \"ngFor\" to iterate over array of objects and show them as matrix having 3 columns f

相关标签:
2条回答
  • 2021-01-03 08:45

    With *ngFor you can iterate over an array. If the array items are arrays, you can nest *ngFor like:

    @Component({
      selector: '...'
      template: `
    <div class="row" *ngFor="let row of matrix">
      <div class="col" *ngFor="let col of row">
       <div class="card">{{col}}</div>
      </div>
    </div>
    `
    })
    class Component {
      matrix = [['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'i']];
    }
    
    0 讨论(0)
  • 2021-01-03 09:02

    If your data are contained within an array of objects. You could use a custom pipe to iterate over object keys:

    @Pipe({name: 'keys'})
    export class KeysPipe implements PipeTransform {
      transform(value, args:string[]) : any {
        if (!value) {
          return value;
        }
    
        let keys = [];
        for (let key in value) {
          keys.push({key: key, value: value[key]);
        }
        return keys;
      }
    }
    

    Here is the way to use it:

    <div class="row" *ngFor="let obj of data">
      <div class="col" *ngFor="let keyValues of obj | keys>
        <div class="card">{{keyValues.key}} = {{keyValues.key}}</div>
      </div>
    </div>
    

    The structure of data used are the following:

    this.data = [
      { prop1: 'val1 a', prop2: 'val2 a', ... }
      { prop1: 'val1 b', prop2: 'val2 b', ... }
      { prop1: 'val1 c', prop2: 'val2 c', ... }
      (...)
    ];
    
    0 讨论(0)
提交回复
热议问题