Reputation: 71
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,
Upvotes: 4
Views: 5466
Reputation: 447
I know that the question is old but i found a way to do a maxtric on data from a single array.
my data structure
data = [
{
from: 'AB',
to : 'AB',
value: true
}
{
from: 'AB',
to : 'CD',
value: false
}
{
from: 'CD',
to : 'AB',
value: true
}
{
from: 'CD',
to : 'CD',
value: false
}
]
Step 1
You need to define what your columns and line head will be. In this case i had the same values of lines and columns.
subsctractHeads(array) {
cols = [ ...new Set(array.map(item => item.from)) ]
}
This will give an array cols = ['AB','CD']
Step 2
Display you data in a table like matrix
<table>
<tr>
<th></th>
<th *ngFor="let column of cols" > {{ column }} </th>
</tr>
<tr *ngFor="let row of cols" >
<th> {{ row }} </th>
<ng-container *ngFor="let dest of cols" >
<ng-container *ngFor="cell to of data" >
<td *ngIf="cell.from === row && cell.to === dest" ></td>
{{ cell.value }}
</ng-container>
</ng-container>
</tr>
</table>
Should display a simple matrix
Upvotes: 0
Reputation: 202138
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', ... }
(...)
];
Upvotes: 1
Reputation: 657058
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']];
}
Upvotes: 2