Универсальное c решение, которое работает с любым configArr
, если все ключи в этом объекте string[]
. Вдохновленный этим .
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>
Stackblitz .
Также см. this для алгоритма позади него.