Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Styling and Binding

In Angular 2 I am binding a dollar value like this inside a TABLE TD.

<td>
  {{eachOutlet.dollarValue}}
</td>

This dollarValue will be less than 0 or equal to 0 or greater than 0. When it is less than zero it should show up in "Red" color. When it is zero, nothing should show up. Just blank text. When it is greater than zero, it should use thousands separator and show the number.

How can I apply such conditional styling using Angular 2 binding? Is it even possible to do it ?

like image 465
Adam Avatar asked Dec 23 '16 17:12

Adam


People also ask

How can you bind styles in Vue JS?

Binding Styles Dynamically To this end, Vue provides us with the v-bind:style directive. On each click event, the v-bind:style directive increments and decrements the value of your fontSize variable. This attaches the value of fontSize to the CSS font-size property.

What is binding in Vue?

The v-bind directive is a Vuejs directive used to bind one or more attributes, or a component prop to an element. If that attribute is binded to our data defined in Vuejs instance then dynamically changes can be observed as data changes.

How do you bind a class?

Class binding with Class There are another shorthand way to bind CSS Class to HTML element. className is name of the class, which you want to bind to. condition must return true or false. A return value of true adds the class and a false removes the class.


3 Answers

<td>
  <span 
    *ngIf="eachOutlet.dollarValue != 0"
    [style.color]="eachOutlet.dollarValue < 0 ? 'red' : null">
      {{eachOutlet.dollarValue | number:'1.0-2'}}
  </span>
</td>

You can also create a directive that does the styling (except the number pipe) to make it easier to reuse over different elements.

Plunker example

like image 109
Günter Zöchbauer Avatar answered Sep 30 '22 02:09

Günter Zöchbauer


Another option for more than one style property:


  • In Template:

<div style="word-break: break-all;" [ngStyle]="{ 'top': getTop() +'px', 'left': getLeft() +'px' }"> </div>

  • And in the Component:

getTop(){
    return (this.topValueShowComment> 0)? this.topValueShowComment : 0;
}

getLeft(){
    return (this.leftValueShowComment> 0)? this.leftValueShowComment : 0;
}
like image 43
Dudi Avatar answered Sep 30 '22 02:09

Dudi


We can do like this.

<div class="responsive-standalone--Overlay" (click)="mobileRMenu()" [style.display]="rMenu ? 'block' :'none'"></div>
like image 3
Mukesh Kumar Bijarniya Avatar answered Sep 30 '22 01:09

Mukesh Kumar Bijarniya