問題:在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);
}
窮人的解決方案是刪除視圖封裝。正確的方法是使用* ngIf來創建和銷燬所需的div,而不是在組件中使用DOM操作。 –
其實,我正在創建一個文件夾管理工具,像[this](https://i-msdn.sec.s-msft.com/dynimg/IC151268.jpg)。用戶可以創建/刪除/展開/摺疊任何文件夾。這就是爲什麼我選擇DOM並放棄ngIf或ngFor。我想要元素在被點擊的文件夾下動態創建。你有更好的主意嗎? –