0

I want to switch between these CSS styles dynamically using a toggle button in angular to make a dark/light mode:

@import '../node_modules/bootswatch/dist/darkly/bootstrap.min.css';
@import '../node_modules/bootswatch/dist/united/bootstrap.min.css';

If possible, what is the cleanest and efficient way to do it?

1 Answers1

4

This is how I solved this problem.I'm gonna leave the answer here in case some finds it useful when running into the same task. It is just a start, feel free to add a transition or extend this method:

1) Copied the bootstrap themes folders into the assets folder as shown:

enter image description here

2) Added a link as the last line of the index.html file so it would override any injected style by Angular:

enter image description here

3) Added a toggle button to my nav component.html template:

<nav>
......
<div class="custom-control custom-switch ml-2">
      <input (click)="changeTheme()" type="checkbox" class="custom-control-input" id="customSwitch1">
      <label class="custom-control-label" for="customSwitch1"></label>
  </div>
</nav>

4) Added the changeTheme() method to the nav.component.ts file:

import { Component, OnInit } from '@angular/core';
....
export class NavComponent implements OnInit {
  isDarkTheme = false;

  constructor() { }

  ngOnInit() {
  }
/** Rest of the methods of the class are hidden **/
  changeTheme(): void {
    if (this.isDarkTheme) {
       document.getElementById('global-theme').setAttribute('href', 'assets/styles/united/bootstrap.min.css');
       this.isDarkTheme = false;
    } else {
       document.getElementById('global-theme').setAttribute('href', 'assets/styles/darkly/bootstrap.min.css');
       this.isDarkTheme = true;
    }
 }
}

4) Here is a demo:

enter image description here