This is my HTML for table
<table class="table table-bordered">
<thead>
<tr>
<th *ngFor="let th of tableHeaders"> {{th}}
<th>
</tr>
</thead>
<tbody *ngIf="tableData.length">
<tr *ngFor="let tr of tableData">
<td *ngFor="let th of tableHeaders; let i = index">{{i}}
<td>
</tr>
</tbody>
</table>
Attached is my output image.
With the value of i its clear i got only 9 columns but the generated columns were 10. You could see a blank column after city.
Why is that? How can i overcome that blank column.
Though it was a miss in <td>
I would like to recommend a better way of handling a common table Component which can be used across application would be as
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<table class="table table-responsive">
<thead>
<tr>
<th *ngFor="let column of tableConfiguration.columns;"
class="col-md-{{column.columnSize}}">
{{column.title}}<th>
</tr>
</thead>
</table>
</div>
`,
})
export class App {
name:string;
tableConfiguration:TableConfiguration;
constructor() {
this.tableConfiguration ={
columns:new Array<Column>()
}
this.tableConfiguration.columns=
[{title: 'First Name',columnSize:3},
{title: 'Last Name',columnSize:3},
{title: 'Contact Number',columnSize:2},
{title: 'Gender',columnSize:2},
{title: 'City',columnSize:2}];
this.name = 'Angular2 Dynamic table'
}
}
export interface TableConfiguration{
columns:Array<Column>;
}
export interface Column{
title:string;
columnSize:number;
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
LIVE DEMO
Note:
- Change the selector as you wish
- ColumnSize should add to 12 as it is default in bootstrap
- Use this to wrap across application by using it inside a CommonModule