2016-10-08 55 views
2
<component> 
    <p class="component-p"></p> 
</component> 

component樣式表:Angular 2如何風格transcluded元素?

.component-p { 
    color: red; 
} 

:host .component-p { 
    color: red; 
} 

:host >>> .component-p { 
    color: red; 
} 

>>> .component-p { 
    color: red; 
} 

::content .component-p { 
    color: red; 
} 

這些都不似乎工作,但我不明白爲什麼。

如果我把::content .component-p放在這個父組件中,那麼它可以工作,但這沒有任何意義,因爲我沒有將它轉化爲父項,而是將其轉化爲component

你是如何定義transcluded內容的?

+0

請張貼正確的代碼並告訴我們你在哪裏使用':host {}'樣式。在父母還是孩子? – micronyks

+0

@micronyks我已經發布了一切。樣式表屬於'component',這只是我嘗試過的簡單事情。關於父母和孩子的部分只是一個例子,在這裏沒有父母。只有'組件'。 – Chrillewoodz

回答

0

注意:有很多方法可以做到這一點。但在這裏,我正在使用你從子組件ng-content element/control如何設計風格子組件

使用:host >>> .component-p選擇transcluded元素,如此處所示。

styles: [` 
       :host >>> .component-p {color:red;} 
     `] 

這個按預期工作。

DEMO:https://plnkr.co/edit/z3urbPNvDXEnJZDMZo74?p=preview

+0

由於某種原因,這也行不通。 – Chrillewoodz

+0

這就是我要求你的代碼。因爲你可以從孩子或父母那裏做。 – micronyks

+0

與沉悶玩耍並告訴我你的問題。 – micronyks

0

爲transcluded元素的風格應該是在使用你的<component>的組件。例如,讓我們說我們有這個組件:

@Component({ 
     selector: 'app-other', 
     template: ` 
      <p>something here</p> 
      <ng-content></ng-content> 
     `, 
}) export class OtherComponent {} 

如果我們用這個在我們app.component,樣式爲走了進去ng-content必須在這裏寫的代碼。

@Component({ 
    selector: 'app-root', 
    template: ` 
     <app-other> 
      <p class="component-p">some things</p> 
     </app-other> 
    `, 
    styles: [` 
     .component-p { 
      color: red; 
     } 
    `] 
}) export class AppComponent {}