问题:在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。我想要元素在被点击的文件夹下动态创建。你有更好的主意吗? –