I would like to apply the CSS to the element created in TypeScript. Is this possible without adding the style in TypeScript (test.style.color = ‘red’;)?
My HTML:
<div class="testContainer">
<p>Created in HTML</p>
<!-- Created in TS-->
</div>
My TypeScript:
ngOnInit() {
let container = document.querySelector('.testContainer')
if(container) {
let test = document.createElement('p');
test.textContent = "Created in TS"
container.append(test)
} else {
console.log('TestContainer not found')
}
}
My CSS:
p {
color: red;
}
I tried to add classes to the elements, created in the TypeScript file. They were displayed in the developer tools of my browser, but the CSS wasn’t applied.
2
Answers
You can directly add class to the element, created in the TypeScript file.
TypeScript Code
CSS
Why not work:
The way Angular manage the .css (to isolate the .css of each element) is adding a prefix in .css. So if you check the .html using F12 in your navigator
You see a .css like
And a .html like
(the _ng-content-ng-c474887881] can be another one, it’s only to explain me.
So, when you create using simple javascript your "divs" has not the attribute _ngcontent-ng-…, and not get the .css
Solutions:
You can use a global .css (adding in styles.css or using
ViewEncapsulation.None), but in this case the .css is applied to all
the application, and to make the .css it’s only to the element
created you need add a class to your element to be more specific the
.css
The another way is use Renderer2
(*) I prefer use a template reference variable and ViewChild,
In your .html
In .ts