2016-08-23 73 views
5

我有一個通用組件,我想在整個應用程序中重用。問題是我想爲網站的各個部分設定不同的風格。這可能嗎?是否可以在Angular 2中設計不同的組件?

我猜測有一種方法可以傳遞styleUrl的路徑,但是這看起來很雜亂,我希望有更好的選擇。

我也試過,但沒有奏效:當指定成分,添加在類,像這樣

<generic-component class="customStyle1"></generic-component> 

,然後添加基於customStyle1到仿製組件的樣式造型,但它似乎沒有拿起風格。

+1

您可以在組件上添加customClass屬性並指定您在每個實例中需要的內容。 –

+0

更新了OP。這是你的意思嗎?我試過了,但沒有奏效。 – user3715648

+0

由於[查看封裝](https://angular.io/docs/ts/latest/guide/component-styles.html#!#view-encapsulation),您可能會遇到問題。可以嘗試在組件上將其指定爲None,或將自定義類添加到不綁定到特定組件的main.css文件中。 –

回答

3

您可以在樣式中使用:host-context以基於您使用的某個類別應用某個類別component

瞭解更多關於它here!!

test.css

:host-context(.theme-green) h3 { 
    background-color: green; 
} 

:host-context(.theme-red) h3 { 
    background-color: red; 
} 

app.component

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <h3 class="title">Basic Angular 2</h3> 
    <my-test class="theme-green" ></my-test> 
    <my-test class='theme-red' ></my-test> 
    ` 
}) 
export class AppComponent { 
    constructor(){} 
} 

test.component

@Component({ 
    selector: 'my-test', 
    template: `<h3>Test Component</h3> 
    `, 
styleUrls : ['./app/test.css'] 
}) 
export class TestComponent { 
constructor(){} 
} 

這裏是Plunker!!

希望這有助於!

3

您可以使用:host(...)選擇與@HostBinding()等組合:

@Component({ 
    selector: 'my-comp', 
    styles: ` 
    :host([type-default]) { 
    background-color: red; 
    } 

    :host([type-header]) { 
    background-color: blue; 
    } 

    :host([type-main]) { 
    background-color: green; 
    } 
` 
}) 
export class MyComponent { 
    @Input() 
    @HostBinding('component-type') 
    componentType:String="type-default" 
} 

,然後切換風格像

<header> 
    <my-comp componentType="type-header"></my-comp> 
</header> 

<main> 
    <my-comp componentType="type-main"></my-comp> 
</main> 

<my-comp></my-comp> 

您也可以從外面你的問題中應用類等,然後使用:host(...)選擇器like

:host(.customStyle1) { 

那麼你不需要這部分

@Input() 
    @HostBinding('component-type') 
    componentType:String="type-default" 

,但如果你想造型與該組件的其它配置設置,結合這種方式可能是有益的。

+0

這很有趣,但是您必須在my-comp組件中定義所有可能的樣式。會不會有一種這種動態的方式?比如,我想在某處使用my-comp,這樣我就可以創建一個包裝器組件,在其中定義我想要的樣式,然後使用'''template:'''' – David

+1

您可以使用' :ng-deep'(之前爲'/ deep /') –

+0

看起來不錯,但它在文檔中說這將在該功能中被棄用。我認爲這對於使用類似組件的不同產品的公司來說是一個非常普遍的問題。是不是有一個「最好」的方法來解決這個問題? – David

相關問題