Shoaib Iqbal
Shoaib Iqbal

Reputation: 2730

Conditional Styling of an Angular component

I am trying to style a component on basis of a condition in following way.

<div class="col-md-3 d-flex justify-content-center align-items-center" ng-style ="{ ' background-color' : (vars.state=='Signup')? '#73c7af' : '#ffffff' }">

and my vars.state=Signup. So it according to this background of this div should be #73c7af but it still white. Can anybody tell me where I am making mistake?

Upvotes: 89

Views: 167709

Answers (2)

JSON Derulo
JSON Derulo

Reputation: 17522

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>

With style binding it's also possible to apply CSS variables which allows moving the actual style declaration to the CSS code:

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

CSS:

.my-element {
  background-color: var(--my-background-color);
}

Upvotes: 157

Nour
Nour

Reputation: 5889

You can use style.propertyName to set any conditional style property.

<div class="col-md-3 d-flex justify-content-center align-items-center" [style.background]="someFunction()">

Upvotes: 28

Related Questions