skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. So the styles loaded were not applied on this appended HTML

    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.

    So, when I use ViewEncapsulation.None, the styles work, but they override the styles in the external parent component too.

    ViewEncapsulation.None basically removes the component’s scope by eliminating attribute selector and effectively make component’s styles global.

    So I want a way to reload the styles when the service returns a response and I append the HTML content to my html and reflect only within my component

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search