79

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?

9
  • post the content of vars
    – Sreemat
    Aug 3, 2017 at 12:55
  • these are all vars vars = { state: '' }; signupData = { name:'', email:'', father_husband:'', address:'', cnic:'', cnincpath:'' }; signatureData= { name:'', signatureurl: '' } verification = { code:{ digit1:'', digit2:'', digit3:'', digit4:'', }, heading:'', message: { top:'', bottom:'' }, button:'next' } And I am setting state to 'Signup' in constructor. Aug 3, 2017 at 12:57
  • 1
    syntax for angular is [ngStyle]="..." Aug 3, 2017 at 12:58
  • This Angular 2 or 1?
    – Sreemat
    Aug 3, 2017 at 13:00
  • 2
    remove the space before background-color in your html. [ngStyle]="{ 'background-color': vars.state=='Signup' ? '#73c7af' : '#ffffff' }"
    – FAISAL
    Aug 3, 2017 at 13:06

2 Answers 2

145

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>
1
  • <div class="col-md-3 d-flex justify-content-center align-items-center" [ngStyle]="{'backgroundColor': (vars.state=='Signup') ? '#73c7af' : '#ffffff'}"> this works also. Mar 18, 2020 at 10:40
26

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()">
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.