Search code examples
angularbootstrap-5darkmode

How to toggle bootstrap dark theme in angular app?


I want to add bootstrap dark theme to my angular application and i don't know how to add data-bs-theme="dark" in index.html using angular? any idea??

I don't know how to change the data-bs-theme attribute using angular


Solution

  • So... you made me curious. For this reason I have tried it. First: This function, or Attribute so to say, is only available in Bootstrap 5.3.0 which still is an Alpha at this time.

    Update:

    Bootstrap 5.3.0 is now official available. So you can use it regular.

    npm install [email protected]

    After this you can use the Attribute. But: In Angular it's not a very good way to manipulate the index.html. It's the main entry of the app and Angular is using the underlying <app-root> as highest level. So we don't need index. You can (and should - so tells us Bootstraps documentation) use it on any components you need, nav or any div.

    In Angular, to make it switchable, bind it as attribute:

    <div [attr.data-bs-theme]="myTheme">
      <!-- Some Stuff -->
    </div>
    

    The code part

    ...
    myTheme: string = "light";
    
    onSwitch() {
      if (this.myTheme === "light")
        this.myTheme = "dark";
      else
        this.myTheme = "light";
    }
    ...
    

    Play around with the docs to see "how to integrate it". But: wrapper like ng-boostrap and so on support this alpha not full at the moment.