implementing ng-if directive inside md-table

16,287

Solution 1

The problem is that you're using two structural directives with an asterisk syntax on one element. You need to unwrap one of them. The following should work:

  <ng-template [ngIf]="!(authService.isAdmin())">
      <md-cell *cdkCellDef="let row">
        <button md-button (click)="viewNarrative(row)"><md-icon>toc</md-icon> Narrative</button>
        <button md-button (click)="editDemographics(row)"><md-icon>edit</md-icon> Demographics</button>
        <button md-button (click)="confirmDelete(row, $event)" style="line-height:normal"><md-icon>delete</md-icon> Delete</button>
      </md-cell>
  </ng-template>

Or simply move ngIf to the ng-container:

<ng-container *ngIf="!(authService.isAdmin())">
    <md-cell *cdkCellDef="let row">

Solution 2

you can do something like:

This allows you to have the mat-cell and an *ngIf too

<ng-container matColumnDef="isActive">
  <mat-header-cell *matHeaderCellDef mat-sort-header> Active </mat-header-cell>
  <mat-cell *matCellDef="let element"> <mat-icon *ngIf="element.isActive;else notactive;">done</mat-icon>
    <ng-template #notactive><mat-icon>clear</mat-icon></ng-template>
  </mat-cell>
</ng-container>

Solution 3

You can apply *ngIf outside md-cell, like this.

<md-row *cdkRowDef="let row;  columns: displayedColumns" (click)="viewNarrative(row)">
  <md-cell *cdkCellDef="let row">
    <button md-button (click)="viewNarrative(row)"  *ngIf="!(authService.isAdmin())"><md-icon>toc</md-icon> Narrative</button>
    <button md-button (click)="editDemographics(row)" *ngIf="!(authService.isAdmin())"><md-icon>edit</md-icon> Demographics</button>
  </md-cell>
</md-row>
Share:
16,287
Admin
Author by

Admin

Updated on June 13, 2022

Comments

  • Admin
    Admin about 2 years

    I'm trying to use ng-if inside my md-table but I'm getting the error:

    Can't have multiple template bindings on one element. Use only one attribute named 'template' or prefixed with * 
    

    Here is my code for the template

    <md-row *cdkRowDef="let row;  columns: displayedColumns" (click)="viewNarrative(row)">
      <md-cell *cdkCellDef="let row" *ngIf="!(authService.isAdmin())">
        <button md-button (click)="viewNarrative(row)"><md-icon>toc</md-icon> Narrative</button>
        <button md-button (click)="editDemographics(row)"><md-icon>edit</md-icon> Demographics</button>
        <button md-button (click)="confirmDelete(row, $event)" style="line-height:normal"><md-icon>delete</md-icon> Delete</button>
      </md-cell>
    </md-row>
    

    when I remove the *cdkCellDef="let row" directive I get the error: ERROR Error: No provider for CdkColumnDef! so how can I implement the ng-if directive?