5

I would like to use my color which is defined in CSS file for my ngStyle directive (which is in HTML).

This is what i've got in my HTML:

 [ngStyle]="{backgroundColor: isDarkStyle() ? '#29434e' : isNormalStyle() ? '#cfd8dc' : isLightStyle() ? 'white': ''}"

This my CSS file with colors:

//colors for background

$light-background: white;
$normal-background: #cfd8dc;
$dark-background: #29434e;

But i want this:

[ngStyle]="{backgroundColor: isDarkStyle() ? '$dark-background' : isNormalStyle() ? '$normal-background' : isLightStyle() ? '$light-background': ''}"

How can I achieve this result? Thanks for help :)

Kacper Kapela
  • 367
  • 2
  • 5
  • 12

3 Answers3

4

Use [ngClass]

See stackblitz:https://stackblitz.com/edit/hello-angular-6-refjye?file=src%2Fapp%2Fapp.component.html

.light{
background: white;
}
.normal{
background: #cfd8dc;
}
.dark{
background: #29434e;
}

in Html

<p [ngClass]="isDarkStyle() ? 'dark' : isLightStyle() ? 'light': isNormalStyle()?'normal':''">
  Start editing to see some magic happen :)
</p>
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
1

try solution

As I understood your queston:

HTML:

<h1 [ngStyle]="{backgroundColor: isDarkStyle() ? 'red' : isNormalStyle() ? 'green' : isLightStyle() ? 'white': ''}">Text</h1>

TS:

isDarkStyle() {
    return false
  }

  isNormalStyle() {
    return true
  }

  isLightStyle() {
    return true;
  }
Akj
  • 7,038
  • 3
  • 28
  • 40
0

You can defined ngClass or ngStyle

ngClass required to define class in your style file

<h1>ngClass</h1>
<p [attr.class]="state">
  Start editing to see some magic happen :)
</p>
<button (click)="state = 'light'">light</button>
<button (click)="state = 'dark'">dark</button>
<button (click)="state = 'normal'">normal</button>

ngStyle you can change spisifc css properties like background-color

<h1>ngStyle</h1>
<p [ngStyle]="{'background-color':color}">
    Start editing to see some magic happen :)
</p>
<button (click)="color = '#fff'">light</button>
<button (click)="color = '#cfd8dc'">dark</button>
<button (click)="color = '#29434e'">normal</button>

stackblitz example

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91