带有if的Angular 5 ngClass

时间:2018-03-28 10:10:35

标签: angular

这是我在表格中的行的代码

  <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>

特定的ngClass代码

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

如果该设备的onlineState处于离线状态,我希望该行拥有该类 highlight device.onlineState either returns Online or Offline如果在线状态为在线状态,则不应该有课程。

3 个答案:

答案 0 :(得分:2)

试试这个。括号中的ngClass,即[ngClass]

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

答案 1 :(得分:2)

您可以执行以下操作:

  [class.highlight]="device.onlineState == 'Offline'"

您必须执行[ngClass]而不是ngClass才能执行表达式。

答案 2 :(得分:2)

ngClass是一个指令,它接受一个对象作为参数,并将类的名称作为属性和条件作为值,例如:

[ngClass]="{'highlight': device.onlineState === 'Offline'}"

您可以添加多个类:

[ngClass]="{'highlight other-class': device.onlineState === 'Offline'}"

[ngClass]="{'highlight': device.onlineState === 'Offline', 'other-class': condition}"