Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mat-table auto fit column width to bigger content

Tags:

css

angular

I have a mat-table I want to auto fit column width, anyone will be as long as the longest column content.

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

 <ng-container matColumnDef="email">
  <mat-header-cell *matHeaderCellDef class="myHeader"> No. </mat-header-cell>
  <mat-cell *matCellDef="let element" class="myCell"> {{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" class="myCell"> {{element.name}} </mat-cell>
 </ng-container>

</mat-table>

Data example:

const DATA: Data[] = [
 {email: '[email protected]', name: 'Long name for this person'},
 {email: '[email protected]': 'name2',
 {email: '[email protected]: 'name3'}
];

So, width cells will be enough for "[email protected]" and for "Long name for this person".

My choices doesnt work, I tried with FxFlexFill and fxFlex unsucced this is my css unsucced option.

.myHeader, .myCell{
  flex: 0 0 100px;
  white-space: nowrap;
}

Can somebody help me?

like image 485
cucuru Avatar asked Feb 08 '18 11:02

cucuru


People also ask

How do I change the width of a column in a mat-table?

Change column width To change the width to a specific measurement, click a cell in the column that you want to resize. On the Layout tab, in the Cell Size group, click in the Table Column Width box, and then specify the options you want.

How do you adjust the width of a matted header in a cell?

In case you want to give a fixed width to a particular column you can add fxFlex="60px" both to mat-cell and mat-header-cell . fixedLayout : Whether to use a fixed table layout. Enabling this option will enforce consistent column widths and optimize rendering sticky styles for native tables.

What is MatColumnDef?

MatColumnDef extends CdkColumnDef Defines a set of cells available for a table column.


2 Answers

You've probably solved this by now, but posting here for anyone else who might come across this.

I used this for reference: https://github.com/angular/material2/issues/5808

It's not an auto-sizing column, but this is how you set widths on specific mat-tablecolumns (the contents wrap by default):

mat-cell:nth-child(1),
mat-header-cell:nth-child(1) {
    flex: 0 0 30%;
}

mat-cell:nth-child(5),
mat-header-cell:nth-child(5) {
    flex: 0 0 10%;
}

If you want to use auto-sizing you'll have to use native <table> as per the solution on this issue: https://github.com/angular/material2/issues/5866

like image 146
metalkat Avatar answered Nov 15 '22 20:11

metalkat


.mat-footer-row,
.mat-header-row,
.mat-row {
    display: inline-flex;
    min-width: 100%;
}

copied from https://fireflysemantics.medium.com/making-the-angular-material-data-table-rows-fit-content-f227f4d9355e

like image 23
Simon H Avatar answered Nov 15 '22 19:11

Simon H