Mixing static and dynamic columns in Angular Mater

2020-05-23 08:53发布

Do any of you know if it's possible to mix dynamic and static columns in mat-table? I'm using it for displaying user data, but i need another column that will show different action buttons regarding the user. Simply adding another ng-container doesn't work since there's no column definition in displayedColumns, but when I add it I'm getting "duplicate error".

<div class="example-container mat-elevation-z8">
<div class="example-header" layout="column" flex="100">
    <md-form-field floatPlaceholder="never">
      <input mdInput #filter placeholder="Filter users">
    </md-form-field>
    <span class="fill-space"></span>
    <button align="right center" md-raised-button color="primary" (click)="clearFilter()">Clear</button>
  </div>
<md-table *ngIf="users && displayedColumns" #table [dataSource]="dataSource">

  <ng-container *ngFor="let set of displayedColumns" [mdColumnDef]="set">
    <md-header-cell *mdHeaderCellDef> {{set}} </md-header-cell>
    <md-cell *mdCellDef="let element"> {{getValue(set, element)}} </md-cell>
  </ng-container>

  <ng-container mdColumnDef="akcje">
    <md-header-cell *mdHeaderCellDef> Akcje </md-header-cell>
    <md-cell *mdCellDef="let element"> asdf </md-cell>
  </ng-container>  <------ this doesn't show another column, when added to displayedColums, produces error

  <md-header-row *mdHeaderRowDef="displayedColumns"></md-header-row>
  <md-row [ngClass]="{'active-user' : current && element.Id == current.Id}" *mdRowDef="let element; let row; columns: displayedColumns;" (click)="gotoUser(element)"></md-row>
</md-table>

2条回答
\"骚年 ilove
2楼-- · 2020-05-23 09:21

Sure, you just need to separate displayedColumns from your dynamic columns array.

<!-- Generic column definition -->
<ng-container *ngFor="let column of columns" [matColumnDef]="...">
  ...
</ng-container>

<!-- Special extra column -->
<ng-container matColumnDef="myExtraColumn">
  ...
</ng-container>

This is basically what you have. You'll iterate over a list of columns to stamp out column definitions, and then add whatever static one(s) you want.

Then you can set displayedColumns - as used by <md-header-row> and <md-row> - to that list of columns with your static column(s) concatenated.

/** Table columns */
columns = [
  ...,
  ...,
  ...,
];

/** List of columns to display in which order */
displayedColumns = this.columns.concat(['myExtraColumn']);
查看更多
贼婆χ
3楼-- · 2020-05-23 09:39

This is Something you all are looking for

displayedColumns = this.columns.map(x => x.name).concat(['actions']);
查看更多
登录 后发表回答