*matCellDef, *matHeaderCellDef and *ngIf in the same container

Viewed 3739

I'm trying to show a part of a row (which are buttons) of my table based on some boolean value but it only seemed to work if I put it on the button level.

I've this code:

    <ng-container matColumnDef="myCol">
      <th class="table-column" mat-header-cell *matHeaderCellDef> myCol </th>
      <td mat-cell *matCellDef="let data">
        <button *ngIf="data.someBoolean" mat-icon-button color="warn">
          <mat-icon class="mat-18">delete</mat-icon>
        </button>
        <button *ngIf="data.someBoolean" mat-icon-button color= "warn">
          <mat-icon class="mat-18">create</mat-icon>
        </button>
      </td>
    </ng-container>

this works but is repetitive. Putting the *ngIf="data.someBoolean" on the container level didn't work. Any ideas how to fix this?

1 Answers

You can reduce duplication of *ngIf="data.someBoolean" by wrapping duplicated code in ng-container:

<ng-container matColumnDef="myCol">
  <th class="table-column" mat-header-cell *matHeaderCellDef> myCol </th>
  <td mat-cell *matCellDef="let data">
    <ng-container *ngIf="data.someBoolean"> <---------------------- common wrapper
      <button mat-icon-button color="warn">
        <mat-icon class="mat-18">delete</mat-icon>
      </button>
      <button mat-icon-button color= "warn">
        <mat-icon class="mat-18">create</mat-icon>
      </button>
    </ng-container>
  </td>
</ng-container>
Related