mat-table auto fit column width to bigger content

2020-07-12 11:27发布

问题:

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: 'mail1@mail.com', name: 'Long name for this person'},
 {email: 'mail2@mail.com': 'name2',
 {email: 'longmailaddres@longmailaddress.com: 'name3'}
];

So, width cells will be enough for "longmailaddress@longmailaddres.com" 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?

回答1:

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



标签: angular css