angularangular-materialangular-material-table

Fix column width in Angular Material Table


I am using Angular material table and trying to fix width for few columns as shown below:

<mat-table #table [dataSource]="dataSource">

 <ng-container matColumnDef="email">
  <mat-header-cell *matHeaderCellDef class="myHeader"> No. </mat-header-cell>
  <mat-cell *matCellDef="let element" > {{element.email}} </mat-cell>
 </ng-container>

 <ng-container matColumnDef="name">
  <mat-header-cell *matHeaderCellDef class="myHeader"> Name </mat-header-cell>
  <mat-cell *matCellDef="let element" > {{element.name}} </mat-cell>
 </ng-container>

</mat-table>

In CSS:

table {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
}

.mat-column-email{
  width: 150px;
}

I read somewhere that we can fix column width by using this format:

.mat-column-matColumnDef(Field name) {
 //CSS
 }

But above format does not seem to work no matter what. Can anyone please help me out with what am I doing wrong ?


Solution

  • After trying lot of things, below solution worked for me:

      .mat-column-email{
           max-width: 60px !important;
           min-width: 60px !important;
        }
    

    So, instead of setting width, set max-width and min-width of that column.