Adam
Adam

Reputation: 1299

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 ?

Upvotes: 37

Views: 56833

Answers (3)

Mukesh Kumar Bijarniya
Mukesh Kumar Bijarniya

Reputation: 466

We can do like this.

<div class="responsive-standalone--Overlay" (click)="mobileRMenu()" [style.display]="rMenu ? 'block' :'none'"></div>

Upvotes: 3

Dudi
Dudi

Reputation: 3079

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

Upvotes: 6

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657396

<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

Upvotes: 68

Related Questions