I try to create elements dynamically in Angular 4.
TS
const bookmark = document.createElement('a');
bookmark.className = 'bookmark';
SCSS
.bookmark {
display: block;
background: white;
color: #999;
padding: 20px;
transition: 0.3s ease all;
border-bottom: 1px solid #DDD;
}
However the style do not apply on the element from the SASS file. If I add the style directly in the JS file, it works:
const bookmark = document.createElement('a');
bookmark.className = 'bookmark';
bookmark.style.display = 'block';
bookmark.style.background = 'white';
bookmark.style.color = '#999';
bookmark.style.padding = '20px';
bookmark.style.transition = '0.3s ease all';
bookmark.style.borderBottom = '1px solid #DDD';
If I create the element directly in the HTML file, it automatically gets a _ngcontent-c1 attribute whilst the one created in TS misses this attribute (if I give it manually in Chrome Developer Tools - Element panel, it gets the style from SCSS).
<div class="bookmarks-list">
<a class="bookmark">
I am the bookmark
</a>
</div>
My question is, how to apply the .bookmark class style from the SASS file to the created bookmark element in TS?
You didn't share the full code, but probably it's the problem with where you create your element, if it's inside a component, it might not reaching your css due to encapsulation , try to use something like below:
@Component({
// ...
encapsulation: ViewEncapsulation.None, //<<<<< this one!
styles: [
// ...
]
})
export class HelloComponent {
// ...
}
For more info, visit the link below: https://angular.io/docs/ts/latest/guide/component-styles.html#!#view-encapsulation