让我们从设置您提供的示例开始,但添加一个我们将用来保持模板清洁的枚举。
some.component.ts
import { Component, OnInit } from '@angular/core';
import { of, Subscription } from 'rxjs'
// Example level enum
export enum RabbitMqResponseLevel {
Low = 'low',
Medium = 'medium',
High = 'high'
}
@Component({
selector: 'my-app',
templateUrl: './some.component.html',
styleUrls: [ './some.component.css' ]
})
export class SomeComponent implements OnInit {
level: RabbitMqResponseLevel;
subscription: Subscription;
constructor() {}
ngOnInit() {
this.subscription = this.simulateRabbitMq.subscribe(
(resp) => {
this.level = resp.Content.level as RabbitMqResponseLevel; // cast the string to our enum.
}
)
}
/**
* returns an observable that we can subscribe to for this demos purpose.
*/
private get simulateRabbitMq() {
return of({
"Source": "",
"Type": "",
"Timestamp": "2019-07-11T06:00:00.000Z",
"Content": {
level: 'medium' // assuming medium is a string.
}
});
}
}
现在我们可以在组件样式文件中编写一些与您的关卡字符串匹配的样式。
some.component.css
.low { color: green; }
.medium { color: orange; }
.high { color: red; }
最后你的模板文件可以保持干净,看起来像这样
some.component.html
Status: <span [ngClass]="level">{{level}}</span>
这会在视觉上给你
这是一个 stackblitz 示例(我在虚假响应之间添加了延迟,因此您可以看到状态将如何随着值的进入而变化)
https://stackblitz.com/edit/angular-changing-color-and-status-dynamically
编辑:为实现此目的的其他方法添加替代解决方案。
您还可以将状态颜色分离到自己的组件中,并更直接地使用枚举中设置的类。这会从我提供的示例中的“应用程序组件”中删除所有垃圾。
在此示例中,我创建了一个新组件,该组件接受关卡输入并将其设置为类。剩下的就是编写 css 以您想要的任何方式响应类。
在这种情况下,我更改了字体颜色以匹配 level,并创建了一个状态块以匹配 level 颜色。
import { Component, Input, HostBinding } from '@angular/core';
import { RabbitMqResponseLevel } from './rabbitmq-response-level.enum';
@Component({
selector: 'level-status',
template: `<span class="status-block"></span><ng-content></ng-content>`,
styles: [`
/* shape of the status block */
:host > .status-block {
display: inline-block;
width: 0.5em;
height: 0.5em;
margin-right: 0.5em;
background-color: black; /* default color */
}
/* status block colors */
:host.low .status-block { background-color: green; }
:host.medium .status-block { background-color: orange; }
:host.high .status-block { background-color: red; }
/* font colors */
:host.low { color: green; }
:host.medium { color: orange; }
:host.high { color: red; }
`]
})
export class LevelStatusComponent {
/**
* This is the input that sets the class based on the enum string.
* It uses HostBinding to class to auto attach the string value
* to the elements class attribute.
*/
@Input()
@HostBinding('class')
level: RabbitMqResponseLevel;
}
app.component.html
Status: <level-status [level]="level">{{level}}</level-status>
这是一个工作实例https://stackblitz.com/edit/angular-changing-color-and-status-dynamically-2