2017-03-16 95 views
0

問題:在angular2中,note.component.css文件不適用於note.component.ts中的動態創建的元素。有誰知道原因?還是這是正確的行爲?angular2 css風格不適用於動態創建的元素?

note.component.css可以用於note.component.html中已有的元素。 如果我把css樣式放在文件「styles.css」中,它就起作用了。如果我使用DOM設置樣式,它的工作。

文件結構:

app 
    components 
     note 
      note.component.css 
      note.component.html 
      note.component.ts 
index.html 
styles.css 

note.component.html:

<div id="section1"></div> 

note.component.css:

button{ 
    background-color: green; //doesn't work 
} 

styles.css的:

button{ 
    background-color: green; //worked 
} 

note.component.ts:

ngOnInit() { 
    var div = document.createElement("button"); 
    div.innerHTML = "Hello world"; 
    // div.style.backgroundColor = "green"; --- worked 
    document.getElementById("section1").appendChild(div); 
    } 
+1

窮人的解決方案是刪除視圖封裝。正確的方法是使用* ngIf來創建和銷燬所需的div,而不是在組件中使用DOM操作。 –

+0

其實,我正在創建一個文件夾管理工具,像[this](https://i-msdn.sec.s-msft.com/dynimg/IC151268.jpg)。用戶可以創建/刪除/展開/摺疊任何文件夾。這就是爲什麼我選擇DOM並放棄ngIf或ngFor。我想要元素在被點擊的文件夾下動態創建。你有更好的主意嗎? –

回答

2

這與組件的ViewEncapsulation做。默認情況下,它被設置爲Emulated,它將所有組件的視圖封裝到單獨的「範圍」中。有固定它的方式有兩種:

1)將封裝到ViewEncapsulation.None

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

@Component({ 
    ... 
    encapsulation: ViewEncapsulation.None 
}) 

2):host /deep/

:host /deep/ button { 
    background-color: green; 
} 

*編輯前綴名你的CSS和是像威廉乙說,你不該不要像這樣操縱DOM。看看#2 here

+0

值得注意的是,語義解決方案不是繼續在你的'ngOnInit'中創建元素,而只是刪除視圖封裝 - 這些都是反模式。相反,他應該在模板中擁有所需的div,並簡單地使用* ngIf –

+0

創建/銷燬它。對,我應該指定正確的方法來執行此操作,但也想給他一個解決方案,以解決他目前正在處理的問題。 – machinehead115

+0

非常感謝您的回答。我會嘗試這兩種解決方案。 –