Angular2 - Set A Different Color to an element Depending On Value

前端 未结 5 1283
臣服心动
臣服心动 2020-12-06 02:28

I am new to Angular2 and was wondering how I go about setting a font color to an element depending on the value.

My scenario is: if the value of the inp

相关标签:
5条回答
  • 2020-12-06 02:56

    Since you use Angular2, So you need to use [ngClass], and your input model is bind to proportion, So use it to compare,

    Do it like :

    <input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion">
    <p>hello <span [ngClass]="{'red': proportion !== '100', 'green': proportion === '100'}">{{username}}</span></p>
    
    0 讨论(0)
  • 2020-12-06 02:57

    You can also bind the style property.

    <span [style.color]="proportion === '100' ? 'green' : 'red'"></span>
    
    0 讨论(0)
  • 2020-12-06 03:03

    You can use it like this:

     <div class="card template-card" [ngClass]="{'z-depth-3': template == selectedTemplate, 'not-selected': !(template == selectedTemplate) && selectedTemplate != null}">
    
    0 讨论(0)
  • 2020-12-06 03:06

    You need to modify your logic to have double quotes and ngModel proportion value

    <input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion">
    <p>hello <span [ngClass]="{red : proportion != '100', green: proportion === '100'}">{{username}}</span></p>
    

    Hope it helps!!

    0 讨论(0)
  • 2020-12-06 03:10

    There are two solutions to change font color but depends on you requirement

    1. If you requirement is change inline style then you can use angular NgStyle Directive which Update an HTML element styles for you..

    NgStyle directive Ex:

    <span [ngStyle]="{'color': proportion === '100' ? 'green' : 'red'}"></span>
    
            ---------------------- OR -----------------------------------
    
    <span [style.color]="proportion === '100' ? 'green' : 'red'"></span>
    
    1. If you requirement is change class then you can use angular NgClass Directive which Adds and removes CSS classes on an HTML element...

    NgClass directive Ex:

    <span [ngClass]="{proportion === '100' ? 'green': 'red'}"></span>
    
    0 讨论(0)
提交回复
热议问题