【问题标题】:Changing color and status dynamically in angular以角度动态更改颜色和状态
【发布时间】:2019-12-31 02:03:38
【问题描述】:

我正在开发一个角度应用程序。我有一个来自 rabbitmq 的 JSON 响应。此响应具有级别参数,其值可以是低、中或高。如果在运行时级别的值很低,那么我想将其表示为示例图像中所示的小矩形颜色和与其相邻的级别。

每个关卡的颜色都应该随着关卡名称而动态变化。我该怎么做?

我的回复看起来像这样

{
    "Source": "",
    "Type": "",
    "Timestamp": "2019-07-11T06:00:00.000Z",
    "Content": {
     level: medium
    }
}

我正在检索如下响应:

this.subscription = this.service.subscribe(resp => {
   this.level = resp.Content.level
}

【问题讨论】:

  • 嘿 :) 你能给我们一个堆栈闪电战的例子吗 :) ?
  • 你能准确地展示一下响应的样子吗?
  • @MsuArven 响应如下: { "Source": "", "Type": "", "Timestamp": "2019-07-11T06:00:00.000Z", "Content" : { 级别:中 } }
  • @Alann 抱歉,到目前为止我还没有任何 stackblitz,但这是一个正常的 JSON 响应,我正在获取并使用订阅我正在访问响应的内容
  • @MsuArven 我已经更新了相关代码

标签: angular angular6 angular7 angular8


【解决方案1】:

您需要创建每个级别值的类基础,例如 low 、 meduim 、 high ..

app.component.css

.medium , .low , .high{
  margin: 1rem;
  border:1px solid currentColor;
  padding: 0.5rem;
}

.medium{
 color: green
}

.low {
color: yellowgreen
}

.high {
  color: red
}

app.component.html

<div *ngFor=" let item of items" [ngClass]="item.Content.level">
    {{item.Content.level}}
</div>

demo ??

【讨论】:

    【解决方案2】:

    让我们从设置您提供的示例开始,但添加一个我们将用来保持模板清洁的枚举。

    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

    【讨论】:

    • 我想给矩形添加颜色而不是文本
    • 您可以使用 css 规则更改正方形的颜色,如我提供的示例所示。 stackblitz 链接显示了如何执行此操作。我也会更新这篇文章,提供一个更好的例子来说明如何分离你的组件以便更容易管理..
    【解决方案3】:

    您可以使用 ngClass https://angular.io/api/common/NgClass

    例子:

    <your-level-element [ngClass]="{'low': parameter.level === 'low', 'medium': parameter.level === 'medium'}">
    

    您将拥有 3 个类(每个级别一个),您可以自定义背景(或任何样式)

    【讨论】:

    • 是的,所以如果值等于 'medium',则只会应用中类
    • 知道了,但对于这个“低”我可以设置背景颜色有一个疑问。但在矩形旁边,我需要显示文本,也将级别指示为 low、medium 或 high 。我该怎么做?
    • 你可以使用css。 .low:after { content: '你的文字; otherStyles... } 否则,您可以创建一个专用组件,您将使用关卡 Input 并使用 ngif 进行游戏
    • 解决方案不可扩展。
    猜你喜欢
    • 2015-05-09
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    相关资源
    最近更新 更多