Angular 13-
I have an external html file that I load in an Angular component. After the file is retrieved and the service returns a response, I append the content to the HTML.
The problem is that the styles are not applied in the scss file.
I want a way to reload this scss file when the response is returned from the service.
I tried adding
setTheme(theme) {
window.localStorage.setItem('theme', JSON.stringify(theme));
this.theme = theme;
let link = document.getElementById("css-theme");
if(link) {
link['href'] = this.theme.url;
} else {
let node = document.createElement('link');
node.href = this.theme.url; // insert url in between quotes
node.rel = 'stylesheet';
node.id = 'css-theme';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
But, I want to refresh the scss file in the angular component, not to append an external link in the head
2
Answers
SCSS is a CSS PRE-processor.
You cannot give your browser an
.scss
file and expect it to work.If you intent to switch your styles this way, the file you link needs to be an
.css
file.By default Angular component styles have a scope of a corresponding component. This is done by adding an attribute selector like
[_xyz123]
, where_xyz123
is an internal random component identifier generated by a compiler. Since you load an HTML from an external source, this HTML doesn’t have those attributes or they don’t match, so the component’s styles are not applied to newly added HTML code.ViewEncapsulation.None
basically removes the component’s scope by eliminating attribute selector and effectively make component’s styles global.What you need is a combination of
ViewEncapsulation.None
with a unique class selector.A unique class selector will prevent component’s styles from leaking outside of your component.
ViewEncapsulation.None
will ensure that component’s styles are applied to the appended HTML.