Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 input field is not 100 then I want it red but if it is 100 then I want it green.

I have the following code in place but cant get it working.

XXX.component.css

.red {
    color: red; 
}

.green {
    color: green;
}

XXX.component.css

<input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion ">
<p>hello <span ng-class='{red : proportion!= '100', green: proportion === '100'}'>{{proportion}}</span></p>
like image 832
murday1983 Avatar asked Jun 08 '17 07:06

murday1983


4 Answers

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>
like image 188
mayur Avatar answered Oct 17 '22 21:10

mayur


You can also bind the style property.

<span [style.color]="proportion === '100' ? 'green' : 'red'"></span>
like image 26
Dmitrij Kuba Avatar answered Oct 17 '22 20:10

Dmitrij Kuba


You can use it like this:

 <div class="card template-card" [ngClass]="{'z-depth-3': template == selectedTemplate, 'not-selected': !(template == selectedTemplate) && selectedTemplate != null}">
like image 1
Jan Giacomelli Avatar answered Oct 17 '22 20:10

Jan Giacomelli


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>
like image 1
anoop Avatar answered Oct 17 '22 21:10

anoop