3

One of my Angular components has two different StyleSheets for a dark and light theme. These should now be displayed depending on which theme is active (normally set via function, in the example simplified by timer). Is it possible to reload only the styling of the Angular component, without reloading the component (and possibly loaded data) completely?


let styleTest = ['button.component.light.scss'];

@Component({
    selector: 'button',
    templateUrl: 'button.component.html',
    styleUrls: styleTest,
})
export class ButtonComponent implements OnInit {

    constructor() {
    }

    public ngOnInit() {
        setTimeout(() => {
            styleTest = ['button.component.dark.scss'];
        }, 5000);
    }
}
3
  • Perhaps this can help you out: stackoverflow.com/a/61874309/8941307. It doesn't relate to angular. It uses css variables. Commented Feb 24, 2021 at 9:20
  • sadly not, becuase in dark and light theme i have an import from extern css sources and i just can define it in this component and not global Commented Feb 24, 2021 at 9:33
  • Perhaps you should share more of your code. Why are you referencing external css files (I assume like bootstrap.css) in just one of your components? Commented Feb 25, 2021 at 6:48

1 Answer 1

1

Maybe something like this can help you:

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);
    }
}

https://github.com/angular/angular-cli/issues/4202

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.