To apply custom width to columns we can create helper classes with width provided in pixels as shown below.
.w-75{
width: 75px;
}
.w-100{
width: 100px;
}
You can add any number of these custom width classes according to your requirements.
After that just add them to the <th>
element in the the table you created.
<ng-container matcolumnDef="id">
<th class="w-75" mat-header-cell *matHeaderCellDef> id </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
<ng-container>
How to Align Text in columns of data-table
In your CSS file just create classes as shown below:
.th-center{
text-align: center;
}
.th-left{
text-align: left;
}
.th-right{
text-align: right;
}
Which we can add to th
elements.
<ng-container matColumnDef="id">
<th class="w-75 th-center" mat-header-cell *matHeaderCellDef> id </th>
<td mat-cell *matCellDef="let element"> {{element.id}} </td>
</ng-container>
For Data-Tables using Component Elements as shown below:
<mat-table [dataSource]="dataList" class="mat-elevation-z8">
<ng-container matColumnDef="id">
<mat-header-cell *matHeaderCellDef [ngClass]="'w-75'"> id </mat-header-cell>
<mat-cell *matCellDef="let element" [ngClass]="'w-75'"> {{element.id}} </mat-cell>
</ng-container>
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef> name </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
</ng-container>
<ng-container matColumnDef="username">
<mat-header-cell *matHeaderCellDef> username </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.username}} </mat-cell>
</ng-container>
<ng-container matColumnDef="email">
<mat-header-cell *matHeaderCellDef> email </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.email}} </mat-cell>
</ng-container>
<ng-container matColumnDef="phone">
<mat-header-cell *matHeaderCellDef> phone </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.phone}} </mat-cell>
</ng-container>
<ng-container matColumnDef="website">
<mat-header-cell *matHeaderCellDef> website </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.website}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
We can use [ngClass]
directive to add classes to Column and Cells but instead of width, we need to use max-width
to columns as well as to cells because components use FLEX layout to define widths.
You can then update CSS classes to the following:
.w-75{
max-width: 75px;
}
.w-100{
max-width: 100px
}
Top comments (0)