Additional Column Created using Angular2 and Boots

2019-09-15 11:48发布

问题:

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.

回答1:

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:

  1. Change the selector as you wish
  2. ColumnSize should add to 12 as it is default in bootstrap
  3. Use this to wrap across application by using it inside a CommonModule