Reputation: 65
I need to create one matrix table of each combination by comparing the two array object using Angular. I am explaining my code below.
ColumnNames= ["Colour", "Size"];
configArr={
"Colour":["Black", "Red", "Blue","Grey"],
"size": ["XS","S","XL","XXL","M"]
}
Here I have two array. My first array ColumnNames
values will be the table column header and accordingly I need to create the matrix like below.
Expected output::
Colour Size
Black XS
Black S
Black XL
Black XXL
Black M
Red XS
Red S
Red XL
Red XXL
Red M
.................
................
................
Like the above format I need to display the data into angular table. I need only create the matrix dynamically.
Upvotes: 1
Views: 2921
Reputation: 2250
A generic solution that works with any configArr
, as long as all keys in that object are string[]
. Inspired by this.
app.component.ts
import { Component, OnInit } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
name = "Angular";
// Comment in/out properties here to see how the table changes
configArr = {
Colour: ["Black", "Red", "Blue", "Grey"],
Size: ["XS", "S", "XL", "XXL", "M"],
//Price: ["$5", "$10", "$15"],
//Brand: ["B1", "B2", "B3"]
};
// This will be an [] of objects with the same properties as configArr
matrix;
allPossibleCases(arr) {
// Taken almost exactly from the linked code review stack exchange link
}
ngOnInit() {
const configKeys = Object.keys(this.configArr);
const arrOfarrs = configKeys.map(k => this.configArr[k]);
const result = this.allPossibleCases(arrOfarrs);
this.matrix = result.map(r => {
const props = r.split(' ');
let obj = {};
for(let i=0;i<props.length;i++) {
obj[configKeys[i]] = props[i]
}
return obj;
});
}
}
app.component.html
<table>
<thead>
<tr>
<th *ngFor="let kv of configArr | keyvalue">{{ kv.key }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let elem of matrix">
<td *ngFor="let kv of elem | keyvalue">{{ kv.value }}</td>
</tr>
</tbody>
</table>
Also, see this for the algorithm behind it.
Upvotes: 1
Reputation: 31
configArr.Colour.forEach((color) => {
configArr.size.forEach((size) =>{
console.log(color ," ", size); // Change this according to your table
})
})
Upvotes: 0
Reputation: 22213
Try like this:
<table>
<tr>
<th *ngFor="let heading of ColumnNames"> {{heading}} </th>
</tr>
<ng-container *ngFor="let color of configArr.Colour">
<tr *ngFor="let size of configArr.size">
<td>{{color}}</td>
<td>{{size}}</td>
</tr>
</ng-container>
</table>
Upvotes: 0