Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 ngClass with a if

Tags:

angular

This is my code for a row in a table

  <tr class="user-item" *ngFor="let device of group.devices" (click)="$event.stopPropagation()" ngClass="device.onlineState == 'Offline' ? 'highlight' : 'highlight2'">
    <td class="qkFix">{{ device.deviceId }}</td>
    <td class="qkFix">{{ device.alias }}</td>
    <td class="qkFix" *ngIf="device.onlineState == 'Online'" ngClass="colorOnline">{{ device.onlineState }}
      <span class="dotOnline"></span>
    </td>
    <td class="qkFix" *ngIf="device.onlineState == 'Offline'" ngClass="colorOffline">{{ device.onlineState }}
      <span class="dotOffline"></span>
    </td>
    <td class="qkFix">
      <button type="button" class="btn btn-default btn-xs" (click)="$event.stopPropagation(); showDevice(device); editDeviceDialog()">
        <i class="material-icons">{{ (auth.hasPermissions(['update-devices'], true)) ? 'edit' : 'open_in_new'}}</i>
      </button>
      <button [disabled]="!(auth.hasPermissions(['delete-devices'], true))" type="button" class="btn btn-default btn-xs" (click)="$event.stopPropagation();deleteDevice(device)">
        <i *ngIf="(auth.hasPermissions(['delete-devices'], true))" class="material-icons" (click)="$event.stopPropagation();deleteDevice(device)">delete</i>
        <i *ngIf="!(auth.hasPermissions(['delete-devices'], true))" class="material-icons" (click)="$event.stopPropagation()">delete</i>
      </button>
      <button *ngIf="device.onlineState == 'Online'" [disabled]="!(auth.hasPermissions(['remote-control'], true))" type="button" class="btn btn-default btn-xs" (click)="$event.stopPropagation(); remoteSession(device)">
        <i *ngIf="(auth.hasPermissions(['remote-control'], true))" (click)="$event.stopPropagation();remoteSession(device)" class="material-icons">swap_horiz</i>
        <i *ngIf="!(auth.hasPermissions(['remote-control'], true))" (click)="$event.stopPropagation()" class="material-icons">swap_horiz</i>
      </button>
    </td>
  </tr>

Specific ngClass code

ngClass="device.onlineState == 'Offline' ? 'highlight' : 'highlight2'"

I want the row to have the class highlight if the onlineState of that device is Offline. device.onlineState either returns Online or Offline. If the onlineState is Online it shouldn't have a class.

like image 898
idontunderstandarrays Avatar asked Feb 12 '26 18:02

idontunderstandarrays


1 Answers

Try with ngClass in brackets i.e. [ngClass]. For more details.

Answer:

 [ngClass]="device.onlineState == 'Offline' ? 'highlight' : 'highlight2'"

If you want to add multiple classes you can do like this:

option1:

 [ngClass]="condition ? 'class1 class2 class3' : 'class4 class5 class6'"

Option2:

[ngClass]="{'class1': condition1, 'class2': Condition2}"
like image 123
Aniket kale Avatar answered Feb 15 '26 11:02

Aniket kale