問題:angular2では、note.component.ts内の動的に作成された要素に対してnote.component.cssファイルが機能しません。誰もその理由を知っていますか?それとも正しい行動ですか?動的に作成された要素に対して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);
}
貧しい人のソリューションは、View Encapsulationを削除することです。適切な方法は、* ngIfを使用して、コンポーネント内でDOM操作を使用する代わりに、目的のdivを作成して破棄することです。 –
実際、[this](https://i-msdn.sec.s-msft.com/dynimg/IC151268.jpg)のようなフォルダ管理ツールを作成しています。ユーザーは任意のフォルダを作成/削除/展開/折りたたむことができます。だから私はDOMを選んでngIfやngForをあきらめているのです。私は要素をクリックしたフォルダの下に動的に作成したい。それ以上のアイデアはありますか? –