I want to provide users with a button to change the theme of the entire website. I use ".scss" boot files for everything. Here is what I did:
I have "dark-styles.scss" and "light-styles.scss" in the "src / styles" folder. Both of these files override the classes and methods that I need to override, as well as import "bootstrap.scss" from the "node-module" for the default values. When I provide any of these files to the application through ".angular-cli.json", as shown below; It works great.
"styles": [ "../node_modules/font-awesome/css/font-awesome.css", "../node_modules/@swimlane/ngx-datatable/release/index.css", "../node_modules/@swimlane/ngx-datatable/release/assets/icons.css", "../src/styles/dark-styles.scss" ],
or,
"styles": [ "../node_modules/font-awesome/css/font-awesome.css", "../node_modules/@swimlane/ngx-datatable/release/index.css", "../node_modules/@swimlane/ngx-datatable/release/assets/icons.css", "../src/styles/light-styles.scss" ],
If I provide a dark theme, dark, and if I provide a light, the theme is light.
But what I want to achieve dynamically allows users to change the theme. Hence, based on other answers in stackoverflow; I accessed the βdocumentβ in my application component, which is also my root component. This gives me access to the entire html page where I have a link tag that I can install from the component application.
HTML file
<head> <link id="theme" type="text/scss" rel="stylesheet" src=""> </head> <body> content ..... </body>
Angular-cli.json
"styles": [ "../node_modules/font-awesome/css/font-awesome.css", "../node_modules/@swimlane/ngx-datatable/release/index.css", "../node_modules/@swimlane/ngx-datatable/release/assets/icons.css" ],
App component:
import { Component, OnInit, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent implements OnInit { currentTheme: string; constructor( @Inject(DOCUMENT) private document) { } ngOnInit() { this.currentTheme = 'dark'; this.document.getElementById('theme').href = '../styles/dark-styles.scss'; } handelChangeTheme(event) { if (this.currentTheme === 'dark') { this.document.getElementById('theme').href = '../styles/light-styles.scss'; this.currentTheme = 'light'; console.log('light'); } else { this.document.getElementById('theme').href = '../styles/dark-styles.scss'; this.currentTheme = 'dark'; console.log('dark'); } } }
When the "handleChangeTheme" event is fired, the href for #theme changes in the html file. But it does not update or apply styles. I understand that it has something to do with WebPack and how it compiles scss files. Has anyone encountered a similar situation or knew a solution to this problem. Thanks