prabhat gundepalli
prabhat gundepalli

Reputation: 967

How to set the width of a column of a dynamic HTML table

I have code as below

 <table >
    <thead >
        <th *ngFor="let col of workData.columns;trackBy: trackByColumn;
            let hindex=index;" [ngClass]="setWidth(col)" [index]="hindex">
        </th>
    </thead>
</table>


 //TS File

  setWidth(col){
   if(col.field === 'First Name') {
   col.width = '100px';
 }
}

In the above table, I get both column names List and column Data from the Http call and render the table based on it. How do I dynamically set width for each column based on its name.

for ex:

Column: First Name Width:100px Column: Last Name Width:90px Column: Address Width: 150px

I am using Angular 6. I tried javascript solutions and also with ngClass and ngStyle in angular. But I am not able to get a handle on how to set width to each of the columns.

Upvotes: 0

Views: 3472

Answers (2)

You can create a JSON object widht a 'style' attribute like this:

workData = { columns: [ { field: "First Name", style: { width: "100px", "background-color": "red", color: "white" } }, { field: "Last Name", style: { width: "200px", "background-color": "blue", color: "white" } }, { field: "Address", style: { width: "300px", "background-color": "yellow", color: "black" } } ]};

then in your file.html

<table>
 <thead>
  <th [ngStyle]="col.style" *ngFor="let col of workData.columns;">{{col.field}}</th>
 </thead>
</table>

now you can add more than one style on your table

click here to see it running

Upvotes: 2

David
David

Reputation: 34435

[ngClass] expects an object. You are calling a method that returns nothing

One possible way is to bind the style property.

component.ts

  public styles=
  {
    'First Name' : '100px',
    'Last Name' : '90px',
    'Address' : '150px'
  };

component.html

 <table >
    <thead >
        <th [style.width]="styles[col.field]" 
            *ngFor="let col of workData.columns; let hindex=index;" >
          {{col.field}}
        </th>
    </thead>
</table>

Stackblitz demo

You could do the same with classes (e.g. class=classes[col.field])

Upvotes: 3

Related Questions