【问题标题】:Angular - Conditional formatting a label with ngIf and ngFor using regex and cssAngular - 使用 regex 和 css 使用 ngIf 和 ngFor 有条件地格式化标签
【发布时间】:2019-07-16 13:47:16
【问题描述】:

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

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

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

【问题讨论】:

    标签: css regex angular ngfor angular-ng-if


    【解决方案1】:

    你需要的是ngStyle

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

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

    【讨论】:

    • 谢谢阿里夫。问题是数据是从不提供属性的 Web 服务中检索的。它返回字符串。所以我需要在 ngfor 上正则表达式这个字符串来检查它是否包含蓝色或红色或绿色等并将其着色为蓝色或红色或绿色等。
    • 这个字符串是什么样的?你能给出一个示例值吗?我可能会帮忙
    【解决方案2】:

    只需向您的组件添加一个函数,它会返回任何颜色。

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

    【讨论】:

    • 你好 MoxxiManagarm,我明白了:includes 不是函数
    • 对我来说效果很好。请谷歌错误信息。
    • 是的,对你来说,它会像你使用数组一样工作。正如我从一开始所说的那样,我想使用正则表达式。
    • 包含只是我的一个例子,因为我不知道你的条件是什么。您可能想为您更改 a,因为在我的示例中 a 是一个字符串。您还需要调整您的条件。我的例子的重点是使用一个字符串返回函数,其中包含条件。
    【解决方案3】:

    终于找到诀窍了

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

    感谢大家的帮助。与正则表达式一起工作正常:)

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多