gary.zhang
gary.zhang

Reputation: 275

angular2 css style doesn't work for dynamicly created element?

Issue: In angular2, note.component.css file doesn't work for dynamically created element within note.component.ts. Does anyone know the reason? Or is it the correct behaviour?

note.component.css can work for element already existed in note.component.html. If I put the css style in file "styles.css", it worked. If I set the style with DOM, it worked.

File structure:

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);
  }

Upvotes: 1

Views: 2339

Answers (1)

machinehead115
machinehead115

Reputation: 1657

This has to do with the ViewEncapsulation of the Component. By default it is set to Emulated which will wrap all of the Component's view into a separate 'scope'. There are two ways of fixing it:

1) Set the encapsulation to ViewEncapsulation.None

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

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

2) Prefix your css with :host /deep/

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

*EDIT and yes like William B said you shouldn't manipulate the DOM like this. Take a look at #2 here

Upvotes: 4

Related Questions