How to use ngFor to display the data as matrix

2020-02-29 05:30发布

问题:

  • 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 for each row. For example;

<div class="row">
  <div class="col">
    <div class="card"></div>
  </div>
  <div class="col">
    <div class="card"></div>
  </div>
  <div class="col">
    <div class="card"></div>
  </div>
</div>
<div class="row">
...
</div>
<div class="row">
...
</div>

Could anyone help me on this? Thanks,

回答1:

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


回答2:

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', ... }
  (...)
];


标签: angular