2017-12-18 245 views
1

對於一個給定的js變量,其具有在它的樣式信息:角2+動態地生成的CSS

menuBgColor = "red"; 

在AngularJS我能夠使用動態地嵌入樣式:

<div> 
    <style> 
     .menuElement{ 
     background-color:{{menuBgColor}} 
     } 
    </style> 
    <div class="menuElement">...</div> 
</div> 

在Angular2 + I不能像上面那樣使用。當視圖在瀏覽器變量中呈現時menuBgColor未被填充,並且元素呈現爲編碼。

這樣的 -

<body> 
...other markup... 
<div><style>.menuElement{background-color:{{menuBgColor}}}</style> 
...markup... 
</body> 

我想知道什麼是角2+等方式來動態樣式添加到視圖?

  • 我知道ngStyle,但給出的例子是一個非常小的例子。
  • 對我而言,我必須將動態樣式應用於整個應用程序的每個元素,例如按鈕,邊框,背景,顏色,樹控件,側邊欄等等。所以ngStyle非常詳盡。
  • 我也沒有預定義的主題文件,因爲主題是由我們的應用程序中的一個功能管理的,用戶可以在其中定義他/她自己的主題。這裏 據我所知,我可以刷新頁面以獲取更新的主題,但考慮到可能有'n'個用戶擁有自己的主題。
  • 所以在我的使用案例中,我能想到的唯一解決方案是以某種方式變量插值並創建嵌入式CSS。

任何幫助,非常感謝。

+0

是吧'menuBgColor'或'菜單。 bgColor'? –

+0

更正,它是'menuBgColor' – Ashwin

+0

像SASS/SCSS的CSS預處理器呢? –

回答

2

你可以試試這個:

<div [style.background-color]="yourVar"></div> 

在這種情況下,應結合工作

+1

好主意,我認爲這將適用於很多情況。但是如果有人想要在僞元素上設置樣式呢? OP還提到(並駁斥)了ngStyle。 –

+1

好,但有很多元素風格。將樣式添加到大約1000個元素是詳盡無遺的。 – Ashwin

2

有沒有漂亮的方式做到這一點無需建立龐大的結構是怎樣的角材料不會。但是,如果你的主題系統不是很複雜,我會簡單地用動態渲染<link>標記你的主題,像這樣走:

import { Component } from '@angular/core' 
import { DomSanitizer } from '@angular/platform-browser' 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <link rel="stylesheet" [href]="getThemeUrl()"> 
    <div class="main"> 
     {{'themes/css/'+ theme +'.css' }} 

     <select [(ngModel)]="theme" (change)="onThemeChanged(theme)"> 
      <option value="red">Red</option> 
      <option value="blue">Blue</option> 
      <option value="yellow">Yellow</option> 
     </select> 
    </div> 
    ` 
}) 
export class AppComponent { 
    theme = 'red'; 

    constructor(public sanitizer: DomSanitizer){} 

    getThemeUrl(){ 
     return this.sanitizer 
      .bypassSecurityTrustResourceUrl('themes/' + this.theme + '.css'); 
    } 
} 

Plunkr

+1

它完美的工作,但只有一個問題是,每個UI交互重新請求CSS文件。任何方式來避免這種情況? – Ashwin

+0

@Ashwin也許如果你使用'[href] =''/ themes/css /'+ theme +'.min.css''' –

+0

@Ashwin是否解決了這個問題? –