How to unload or reload a SCSS for an Angular 11 component?

Viewed 232

As far as I understood, Angular doesn't remove any <styles> on component destruction. But is there a way to reload a SCSS on dynamic component creation?

What I want to achieve? I have a container that shall show different components of the same type. The components need to have the same class-name scoreboardContent:

Container
---------
    Cycle1  click -> load TextComponent with style#1
            click -> load TextComponent with style#2
            click -> load TextComponent with style#3

    Cycle1  click -> load TextComponent with style#1    -> PROBLEM: it shows CSS of style#3
            click -> load TextComponent with style#2    -> PROBLEM: it shows CSS of style#3

On each click a TextComponentis created dynamically with the typical "Angular way", like:

...
container.clear();
const cfr = AppInjector.get(ComponentFactoryResolver);
const factory = cfr.resolveComponentFactory(template);
this.componentRef = container.createComponent(factory);

container.insert(this.componentRef.hostView);
...

This works fine for the first cycle. But in second cycle always shows the CSS of style#3. This is obvious because in <head> exists now styles for style#1,style#2 and style#3, and they overwrite each other.

To resolve this issue, I try to remove the unused style from the <head> with something like that:

var styles = document.getElementsByTagName('style');

for (var i = 0, max = styles.length; i < max; i++) {
    if (/scoreboardContent/.test(styles[i]?.innerHTML)) {
        styles[i].parentNode.removeChild(styles[i]);
    }
}

That also works for the first cycle, but later the style is not created anymore. In other words: there is not scoreboardContent class available anymore. So my questions are now:

  • Why doesn't Angular create a new style in second cycle? I expected that dynamically created components will also create the styles? Is there a way to force it?
  • Is there maybe a different approach to achieve the desired behaviour? (I saw en example to load a CSS-file via a service, but this is not applicable because SCSS is necessary to be used)

Thx for any hints and solutions!

0 Answers
Related