Angular: добавление условного класса с использованием [ngClass]

Во многих приложениях есть элементы, которые меняют свой стиль в зависимости от различных условий. В этой статье я покажу вам несколько способов их добавления с помощью директивы [ngClass].

Одно состояние

приложение.component.html:

<div class="square" [ngClass]="{'low': temperature === 0}"></div>
<button (click)="onLowTemperature()">Low temperature</button>

app.component.ts:

temperature: number = 50;
onLowTemperature() {
  this.temperature = 0;
}

приложение.компонент.css:

.square {
  height: 100px;
  width: 100px;
  margin: 5px 0;
  background-color: grey;
}
.low {
  background-color: blue;
}

Результат:

Два условия

приложение.component.html:

<div class="square" [ngClass]="{'low': temperature === 0, 'medium': temperature === 40}"></div>
<button (click)="onLowTemperature()">Low temperature</button>
<button (click)="onMediumTemperature()">Medium temperature</button>

app.component.ts:

temperature: number = 50;
onLowTemperature() {
  this.temperature = 0;
}
onMediumTemperature() {
  this.temperature = 40;
}

приложение.компонент.css:

.square {
  height: 100px;
  width: 100px;
  margin: 5px 0;
  background-color: grey;
}
.low {
  background-color: blue;
}
.medium {
  background-color: orange;
}

Результат:

Другой синтаксис

<div class="square" [ngClass]="{temperature === 0 ? ‘low’ : ‘medium’">

Этот синтаксис означает, что если температура равна 0, класс будет «низким». Во всех остальных случаях будет добавлен «средний» класс.

Несколько условий

приложение.component.html:

<div class="square" [ngClass]="{
'low': temperature === 0, 
'medium': temperature === 40, 
'high': temperature === 80}"></div>
<button (click)="onLowTemperature()">Low temperature</button>
<button (click)="onMediumTemperature()">Medium temperature</button>
<button (click)="onHighTemperature()">High temperature</button>

app.component.ts:

temperature: number = 50;
onLowTemperature() {
  this.temperature = 0;
}
onMediumTemperature() {
  this.temperature = 40;
}
onHighTemperature() {
  this.temperature = 80;
}

приложение.компонент.css:

.square {
  height: 100px;
  width: 100px;
  margin: 5px 0;
  background-color: grey;
}
.low {
  background-color: blue;
}
.medium {
  background-color: orange;
}
.high {
  background-color: red;
}

Результат:

Начальное состояние

приложение.component.html:

<div class="square" [ngClass]="currentTemperatureClass"></div>

app.component.ts:

currentTemperatureClass: Record<string, boolean> = {};
temperature: number = 0;
ngOnInit() {
  this.setClasses();
}
setClasses() {
  this.currentTemperatureClass = {
  low: this.temperature === 0,
  medium: this.temperature === 40,
  high: this.temperature === 80
}

приложение.компонент.css:

.square {
  height: 100px;
  width: 100px;
  margin: 5px 0;
  background-color: grey;
}
.low {
  background-color: blue;
}
.medium {
  background-color: orange;
}
.high {
  background-color: red;
}

Заключение

Как видите, благодаря директиве ngClass мы можем добавлять классы по-разному, в зависимости от разных условий.