Conditional Styling of an Angular component

To conditionally style a DOM element, there are multiple options for Angular 2+:

NgStyle

This is very similar to the AngularJS ng-style implementation and allows multiple styles by adding more object properties.

<div
  [ngStyle]="{'background-color': (vars.state=='Signup') ? '#73c7af' : '#ffffff'}"
></div>

Style binding

Alternatively, you can use the [style.] binding syntax. If you want to set multiple different styles, you need to add the attribute multiple times.

<div
  [style.background-color]="(vars.state=='Signup') ? '#73c7af' : '#ffffff'"
  [style.color]="myColor"
></div>

Leave a Comment