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

user10192769 picture user10192769 · Jan 9, 2019 · Viewed 9k times · Source

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.

Answer

CBarr picture CBarr · Jan 9, 2019

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>