2016-11-15 49 views
4

爲Angular 2應用程序實現插件式CSS主題的最佳方式是什麼? 什麼是推薦的文件結構?目前我正在使用angular-cli生成的一個。Angular 2中的CSS主題

+0

文件結構將是你最好的選擇。這是人們大部分時間用來構建適用於生產的angular2應用程序的工具。 –

+0

我同意,這就是爲什麼我使用它。但是CSS主題呢? –

回答

0

我們有幾個辦法樣式添加到組件:

  • 內嵌在HTML模板
  • 通過設置樣式或styleUrls元
  • 與CSS進口

內聯樣式:

@Component({ 
    templateUrl: 'test.html', 
    styles: [` 
    .card { 
     height: 20px; 
     width: 80px; 
    } 
    `], 
}) 

使用外部的樣式表:

@Component({ 
    styleUrls: ['css/mystyle.css'], 
    templateUrl: 'test.html', 
}) 

CSS進口:

@import 'hero-details-box.css'; 

組件樣式也有從陰影DOM風格作用域的世界特殊選擇。例如可以應用到文檔中的CSS主題類:

:host-context(.theme-light) h2 { 
    background-color: #eef; 
} 

作爲一種常見的做法,在同一個目錄拆分組件的代碼,HTML和CSS爲三個單獨的文件:

quest-summary.component.ts 
quest-summary.component.html 
quest-summary.component.css 

請訪問Component styles瞭解更多信息。

如果您想進一步增強它並使用SAS訪問ANGULAR2 SASS瞭解更多詳情。

styleUrls: ['./sassexample.component.scss'] 

如果你想使用一個庫UI comnponents請結帳以下:

PrimeNG

Material

NG bootsrap

希望這有助於。

乾杯!

+1

我知道,那不是我問的。我問了關於CSS主題。你會如何在上面的例子中插入一個外部CSS主題? –

+0

對不起,我現在得到它,請看看更新的答案。 –

+0

我的問題不是關於UI組件庫。假設我想創建我自己的組件並添加主題。 –

0

Angular cli內置了對css預處理器的支持,如sass和less,這對於css主題非常有用。這個問題比較好解決,如果你專注於如何通過以下/上海社會科學院做主題則是如何做到這一點的角度

我會建議有你的根組件下面的根元素:

應用。 component.html

<div [ngClass]="theme"> 
    <div class="widget">TEST</div> 
</div> 

app.component。通過角CLI提供TS

import { Component, OnInit, ViewEncapsulation } from '@angular/core'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.scss'], 
    encapsulation: ViewEncapsulation.None // this allows parent styles to influence children 
}) 
export class AppComponent implements OnInit { 
    public theme: string; 

    constructor() {} 

    public ngOnInit(): void { 
     this.theme = ... some logic to set theme here ... 
    } 
} 

app.component.scss

.theme1 { 
    .widget { 
     background-color: red; 
    } 
} 

.theme2 { 
    .widget { 
     background-color: blue; 
    } 
} 

This is just a simple example, A quick google reveals many in depth guides on how do to theming in sass

+2

我知道該怎麼做主題化的無禮。我的問題是,如果有一種標準的方式來組織Angular 2中的主題/主題文件。我懷疑沒有。你的想法很不錯,但是如果我不想加載CSS中的所有主題呢? –