-1

In my app I have a bunch of different material tables. I want to find some way to automatically set column width.

I know, I can set this directly in CSS like this and I try this

.mat-column-position {
  flex: 0 0 10%;
}
.mat-column-name {
  flex: 0 0 25%;
}
.mat-column-weight {
  flex: 0 0 25%;
}
.mat-column-symbol {
  flex: 0 0 25%;
}

But in this way, I need to manually set the width for every table.

I also try dynamically set CSS with SCSS

@mixin mat-table-columns($columns)
{
    .mat-column-
    {
        @each $colName, $props in $columns {

            $width: map-get($props, 'width');

            &#{$colName} 
            {
                flex: $width;
                min-width: $width;

                @if map-has-key($props, 'color') 
                {
                    color: map-get($props, 'color');
                }
            }  
        }
    }
}

@include mat-table-columns((

    orderid: (width: 6rem, color: gray),
    date: (width: 9rem),
    items: (width: 20rem)

));

But in all of these ideas, I need to manually set the width.

I try to find, is there any way to automatically set the width relative to the string with the longest length

| abc   | abcdefg | abcdefgh |
| abcde | abc     | abc      |
| ab    | abcdef  | abc      |

Here is stackblitz for example. Thnx

Arter
  • 2,224
  • 3
  • 29
  • 66

2 Answers2

2

I would recommend using native table elements, this way your cells will auto resize and you should never have to worry about setting them manually.

  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

https://stackblitz.com/edit/angular-8kyrsp-gnhbfd?file=src%2Fapp%2Ftable-flex-basic-example.css

robbieAreBest
  • 1,601
  • 14
  • 16
0

As robbieAreBest suggested, the native table element will resize. What I didn't know is that all that needs to be done is this:

<table mat-table>
    your table
</table>

instead of (old way)

<mat-table>
    your table
</mat-table>

See docs for more info

Sofía
  • 784
  • 10
  • 24