web-dev-qa-db-ja.com

Angular 6、ngStyleディレクティブのcssファイルからの色

ngStyleディレクティブ(HTML)にCSSファイルで定義されている色を使用したいと思います。

これは私が私のHTMLに持っているものです:

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

これは色付きの私のCSSファイルです:

//colors for background

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

しかし私はこれが欲しい:

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

どうすればこの結果を達成できますか?手伝ってくれてありがとう :)

4
Kacper Kapela

使用する [ngClass]

Stackblitzを参照してください: https://stackblitz.com/edit/hello-angular-6-refjye?file=src%2Fapp%2Fapp.component.html

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

hTMLで

<p [ngClass]="isDarkStyle() ? 'dark' : isLightStyle() ? 'light': isNormalStyle()?'normal':''">
  Start editing to see some magic happen :)
</p>
3

解決策を試す

私があなたの質問を理解したように:

HTML:

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

TS:

isDarkStyle() {
    return false
  }

  isNormalStyle() {
    return true
  }

  isLightStyle() {
    return true;
  }
0
Akj

ngClassまたはngStyleを定義できます

ngClassスタイルファイルでクラスを定義するために必要

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

ngStylebackground-colorのようなspisifccssプロパティを変更できます

<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の例

0
malbarmavi