Friday, 11 October 2019

Construct the dynamic table with specified number of columns on each row as per the size of the data in Angular

The below code is to generate a table with multiple rows with the specified number of columns on each row as per the size of the data array.
// Filename: property-detail.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-property-detail',
templateUrl: './property-detail.component.html'
})
export class PropertyDetailComponent {
constructor() {
this.items = this.constructArrayToMultiRows(this.getPropertyDetail(), 3);
}
getPropertyDetail() {
return [
{
'title': 'Customer Category',
'value': 'Bank Customer'
},
{
'title': 'Customer Code',
'value': '11111112'
},
{
'title': 'Start Date',
'value': '2015-09-01'
},
{
'title': 'VAT Code',
'field': 'vat_code',
'value': '13313AS123'
},
{
'title': 'Gender',
'value': 'Male'
},
{
'title': 'Is Legal',
'value': 'True'
},
{
'title': 'Customer Type',
'value': '2'
},
];
}
constructArrayToMultiRows(items: any, columnsPerRow = 4) {
const rows = [];
let total = items.length;
const totalRow = Math.ceil(total / columnsPerRow);
let count = 0;
for (let row = 0; row < totalRow; row++) {
const columns = [];
for (let column = 0; column < columnsPerRow && total > 0; column++) {
columns[column] = items[count];
count++;
total--;
}
rows.push(columns);
}
return rows;
}
}
<!-- Then, create the file (property-detail.component.html) with below content: -->
<table width="100%" class="table table-striped table-bordered" *ngIf="items.length > 0">
<tbody *ngFor="let row of items">
<tr>
<td *ngFor="let column of row" width="20%"> {{ column.title }}: </td>
</tr>
<tr>
<td *ngFor="let column of row"><strong>{{ column.value }}</strong> </td>
</tr>
</tbody>
</table>

Then, on the output, we would be able to generate a table with multiple rows with a specified number of columns.

No comments:

Post a Comment

Please post any queries and comments here.