Implementing if else condition inside a mat-cell of a mat-table - Angular 5

Viewed 17314

I am trying to implement an if else condition inside a mat-cell of a mat-table in my angular application. But I am getting error from the console "ERROR Error: StaticInjectorError(AppModule)[NgIf -> TemplateRef]: "

my code is

<ng-container matColumnDef="role">
    <mat-header-cell *matHeaderCellDef>Role</mat-header-cell>        
    <mat-cell *matCellDef="let user" ngIf="{{user.roles.length == 1}}">
        Admin          
    </mat-cell>
  </ng-container>

Any help is much appreciated.

4 Answers

you have ngIf, but it should be prefixed with an asterisks: *ngIf

Also, with a bound directive attribute like *ngIf you don't need to use the curly braces inside of that. Just doing *ngIf="user.roles.length == 1" should be fine.

However, usually you can't have two directives on the same element with asterisks, so using another <ng-container> is probably the way to fix this:

<ng-container matColumnDef="role">
  <mat-header-cell *matHeaderCellDef>Role</mat-header-cell>
  <ng-container *ngIf="user.roles.length == 1">
    <mat-cell *matCellDef="let user" >
      Admin          
    </mat-cell>
  </ng-container>
</ng-container>

I have faced for a same kind of issue.. And i came up with following solutions.

  1. You can use [ngClass] as follows.
  <tr mat-footer-row [ngClass]="dataSource.length==0 ? 'hide' : ''" *matFooterRowDef="displayedColumns1"></tr>
  1. Or If you want to hide some cells you can use [hidden] attribute. It's like CSS "display: none" property.
  <tr mat-footer-row [hidden]="dataSource.length==0" *matFooterRowDef="displayedColumns1"></tr>

Adding a wrapper ng-container did the trick getting the user object on parent container and using that paren accessed variable in child container for *ngIf.


    <ng-container matColumnDef="role">
      <th *matHeaderCellDef mat-header-cell>Role</th>
      <td *matCellDef="let user" mat-cell>
        <ng-container *ngIf="user.roles.length == 1;else conditionNotMet">
          Admin (Condition is met)
        </ng-container>
      </td>

      <ng-template #conditionNotMet>
        What ever logic...
      </ng-template>
    </ng-container>

You can use a class to set the display as none and will make the trick

<ng-container matColumnDef="role">
<mat-header-cell *matHeaderCellDef>Role</mat-header-cell>        
<mat-cell *matCellDef="let user" [ngClass]="'hide':user.roles.length == 1">
    Admin          
</mat-cell>

And in your stylesheet file

.hide {
  display: none;
}
Related