2

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?

  • You can put `*ngIf="data.someBoolean"` in `ng-container`. – yurzui May 06 '20 at 09:40
  • 1
    @yurzui i did, but it had no effect. Am i missing something? The error was there that `data` is no defined –  May 06 '20 at 09:41
  • Yes, looks like you added it at top level `ng-container` but it should be another `ng-container` – yurzui May 06 '20 at 09:44

1 Answers1

1

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>
yurzui
  • 205,937
  • 32
  • 433
  • 399