2017-03-16 107 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

非常感谢您的回答。我会尝试这两种解决方案。 –