Can the width of a column be altered in a sortable primeng table?

Vaibhav Tiwari picture Vaibhav Tiwari · Jun 25, 2018 · Viewed 10.4k times · Source

I want to reduce the width of a few columns I'm using in primeng grid. However as per my understanding, we can only change the width of columns we create using "p-column" or the "th" tag.

PFA code snippets below: HTML:

 <th *ngFor="let col of columns" [pSortableColumn]="col.field"colspan="col.colspan" style="text-align: 
center;">
                {{col.header}}
                <p-sortIcon [field]="col.field"></p-sortIcon>
      </th>

And the TS:

this.cols = [
                { field: 'first', header:'FIRST'},
                { field: 'second', header: 'SECOND'},
                { field: 'third', header: 'THIRD'},
                { field: 'fourth', header: 'FOURTH'},
                { field: 'fifth', header: 'FIFTH'},
                { field: 'sixth', header: 'SIXTH'}
            ];

How can we change the width for a dynamic column in sortable primeng table?

Answer

Vaibhav Tiwari picture Vaibhav Tiwari · Jun 26, 2018

updated TS file as, Pass the required width value similar to that of header name for the dynamic columns:

this.cols = [
{field: 'first', header: 'FIRST', width: '20%'},
{field: 'second', header: 'SECOND', width: '30%'},
{field: 'third', header: 'SECOND', width: '50%'}]

Use ngStyle attribute to bind the value of width:

eg:

<th *ngFor="let col of columns" [pSortableColumn]="col.field" colspan="col.colspan" 
       [ngStyle]="{'width': col.width}">
                {{col.header}}
       <p-sortIcon [field]="col.field"></p-sortIcon>
</th>