角材料表-将宽度分配给动态表中的特定列

时间:2019-07-18 08:55:19

标签: angular angular-material

我有一个动态的角材料表组件,其工作原理如下:

<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>

该组件接受列列表,例如:

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

它可以工作,但是我正在尝试对其进行增强,并将width属性发送到其中一列(可以是任意列)。例如:

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

如何根据属性调整列宽?我不想基于CSS中的此列标题对类名进行硬编码(因为它将不再是动态的)。请注意,宽度仅适用于特定的列。

我尝试按如下方式更新Mat-cell flex样式属性:

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

但是它弄乱了其余列的宽度(我想它会覆盖当前的flex属性,我不知道默认值是什么)

有什么主意吗?

1 个答案:

答案 0 :(得分:1)

我正在使用Angular CLI版本。 9,以下经过测试!

只需使用MatTable [width]="column.width"的@Input()属性

例如

<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>