Angular - 使用正则表达式和 css 使用 ngIf 和 ngFor 条件格式化标签

Angular - Conditional formatting a label with ngIf and ngFor using regex and css

我想根据从 Web 服务获得的数据有条件地为某些标签着色。 Web 服务工作正常,数据被保存到数组 b.

例如, 如果标签包含 "blue",将其涂成蓝色, 如果标签包含 "red",则将其涂成红色 等等 我最多有 6 个条件。

  <div class="centered">
        <h2>List of labels </h2>
                <label *ngFor="let a of b">  
                    {{a.x}}  
                  </label>
    </div>

你需要的是ngStyle.

<div class="centered">
        <h2>List of labels </h2>
        <label *ngFor="let a of b" [ngStyle]="{color: a.color}">  
           {{a.x}}  
        </label>
</div>

或者要求您的服务器提供类名并使用 [ngClass]

只需向您的组件添加一个功能,returns任何颜色。

        <h2>List of labels </h2>
        <label *ngFor="let a of listA" [ngStyle]="{color: findColor(a)}">  
           {{a}}  
        </label>

示例:

listA: string[] = ['I am red.', 'I am blue.', 'I am normal.']

  findColor(a: string): string {
    if(a.includes('red')) {
      return "#ff0000";
    }
    if(a.includes('blue')) {
      return "#0000ff";
    }
    return null;
  }

终于找到窍门了

HTML

<div class="centered">
        <h2>List of labels </h2>
                <label *ngFor="let a of b" [ngStyle]=" {color:findColor(a.x)}">

                    {{a.x}}  
                  </label>
    </div>

打字稿

public findColor(a: string): string {

      var blue = a.match(/blue/);
      var red = a.match(/red/);
      if(red) {
        return "#ff0000";
      }
      if(blue) {
        return "#0000ff";
      }
      return null;
    }

感谢大家的帮助。适用于正则表达式 :)