Ngx-datatable set column width dynamically

You can set your desired width for column in your table column definition. for exmaple:

  providersColumns = [
            { prop: 'id', name: 'ID', sortable: true, width: -100 },
            { prop: 'name', name: 'Name', sortable: true },
            { prop: 'email', name: 'Email', sortable: true ,width:50}

Btw there is a tricky point here !!! Ngx-datatable set a fixed width for every column if you want to increase that width you should set a positive number that this number will add to the Ngx-datatable width i mean if you set 50 as width ,50 will add to Ngx-datatable fixed width : 50 + x ( Im not sure but i think it was 130 PX for every column)

so final width for email column will be 50+130 =180 PX

or if you want to decrease that width you should set a negative number that this number will add to the Ngx-datatable width i mean if you set -100 as width ,-100 will minus Ngx-datatable fixed width : -100 + x

final width for id column will be -100+130 =30 PX


You need to set column width along with [columnMode]="force", like this:

app.component.html

<ngx-datatable
  class="material"
  [rows]="rows"
  [loadingIndicator]="loadingIndicator"
  [columns]="columns"
  [headerHeight]="50"
  [footerHeight]="50"
  [rowHeight]="'auto'"
  [reorderable]="reorderable"
  columnMode="force">
</ngx-datatable>

app.component.ts

  columns = [
    { name: 'Name', prop: 'name'},
    { name: 'Gender', prop: 'gender'},
    { name: 'Company', prop: 'company', sortable: false }
  ];

  rows = [
    {name: "A", gender: "male", company: "abc"},
    {name: "B", gender: "female", company: "abc"},
    {name: "C", gender: "male", company: "abc"}
  ];

  columnWidths = [
    {column: "name", width: 50},
    {column: "gender", width: 100},
    {column: "company", width: 150}
  ]

  ngOnInit() {
    this.columns.forEach((col: any) => {
      const colWidth = this.columnWidths.find(colWidth => colWidth.column === col.prop);
      if (colWidth) {
        col.width = colWidth.width;
      }
    });
  }

If you use the solution of Hoang Duc Nguyen, you can also store the width in the columns:

 columns = [
    { name: 'Name', prop: 'name', width: 250},
    { name: 'Gender', prop: 'gender'},
    { name: 'Company', prop: 'company', sortable: false }
  ];

You can create custom ngx-datatable-column templates and use [width] prop like:

<ngx-datatable-column name="Name" prop="name" [width]="200">
    <ng-template let-name="value" ngx-datatable-cell-template>
        {{name}}
    </ng-template>
</ngx-datatable-column>


<ngx-datatable-column name="Gender" prop="gender" [width]="100">
    <ng-template let-gender="value" ngx-datatable-cell-template>
        {{gender}}
    </ng-template>
</ngx-datatable-column>


<ngx-datatable-column name="Company" prop="company" [width]="300">
    <ng-template let-company="value" ngx-datatable-cell-template>
        {{company}}
    </ng-template>
</ngx-datatable-column>