Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh Angular Style

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);
    }
}
like image 541
andy Avatar asked Feb 01 '26 02:02

andy


1 Answers

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

like image 82
Javier Martínez Avatar answered Feb 03 '26 22:02

Javier Martínez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!