Angular:使用 「ngClass」 添加条件类

发布一下 0 0
Angular:使用 「ngClass」 添加条件类

许多应用程序的元素会根据不同的条件改变其样式。 在本文中,我将向您展示使用 [ngClass] 指令添加它们的几种方法。


一个条件

app.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;}


app.component.css:

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


结果:

Angular:使用 「ngClass」 添加条件类


两个条件

app.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;}


app.component.css:

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


结果:

Angular:使用 「ngClass」 添加条件类


另一种语法

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

此语法意味着如果温度为 0,则类别将为“低”。 在任何其他情况下,将添加“中”类。


多个条件

app.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;}


app.component.css:

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


结果:

Angular:使用 「ngClass」 添加条件类


初始条件

app.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}


app.component.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 指令,我们可以根据不同的条件以不同的方式添加类。

版权声明:内容来源于互联网和用户投稿 如有侵权请联系删除

本文地址:http://0561fc.cn/94086.html