Search code examples
cssregexangularngforangular-ng-if

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


I want to conditionnally color some labels from data I get from a web service. The web service works fine and the data gets saved to an array b.

For example, if the label contains "blue", color it blue, if the label contains "red", color it red etc. I'll have max 6 conditions.

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

Solution

  • Finally I've found out the trick

    The HTML

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

    The typescript

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

    Thanks all for your help. Works fine with regex :)