0
votes

I have a dynamic angular material table component, that works like this:

<table mat-table [dataSource]="dataSource" class="table"
       matSort>

  <ng-container *ngFor="let column of columns" [matColumnDef]="column.key">
    <mat-header-cell *matHeaderCellDef mat-sort-header>
      {{column.name}}
    </mat-header-cell>
    <mat-cell *matCellDef="let row"
              [@getIn]>
            {{row[column.key] || 'N/A'}}
    </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"
           matRipple
           [matRippleDisabled]="!allowSelect"
           [class.selectableRow]="allowSelect"></mat-row>
</table>

The component accepts a list of columns, for example:

[{
   key: "date",
   name: "Date",
}, {
   key: "title",
   name: "Book Name",
}]

It works, but I'm trying to enhance it and send width attribute to one of the columns (it can be any). For example:

[{
       key: "date",
       name: "Date",
       width: 110
    }, {
       key: "title",
       name: "Book Name",
    }]

How I can adjust the columns width based on thie attributes? I do not want to hardcode the class name based on this column title in the CSS (as it won't be dynamic anymore). Please note that the width is applied only to specific columns.

I tried to update the mat-cell flex style attribute as follows:

<mat-cell *matCellDef="let row"
              [@getIn]
              [style.flex]="column.width ? '0 0 ' + column.width + 'px' : null">

but it messes up the width of the rest of the columns (I guess it overwrites the current flex attribute, and I have no idea what the default is)

Any idea?

1
Please read my question, the column can be anything, I don't want to specifically assign class for each, those can change.TheUnreal
If what you want is autosizing columns then you have to use the native tableLuis Rico
I did, but it's not clear what you want, to change the width based on what attributes?Luis Rico
I want the column width change based on the width send along with the column object (column.width). I updated my question with examples of the inputTheUnreal

1 Answers

1
votes

I am working in Angular CLI ver. 9, and following is tested!

Simply use @Input() property of MatTable [width]="column.width"

e.g.

<ng-container matColumnDef="Column">
        <th mat-header-cell *matHeaderCellDef> Column Name </th>
        <td [width]="element.width" mat-cell *matCellDef="let element"> {{element.manuscriptNumber}} </td>
</ng-container>