How to dynamically change Bootstrap v5.3 primary color at runtime in Angular v17?

Discussão em 'Angular' iniciado por Code with Benji, Fevereiro 26, 2025.

  1. I am working on an Angular application that uses Bootstrap for styling. I want to allow users to select a theme color, and dynamically update the Bootstrap primary color (--bs-primary) at runtime without reloading the page.

    Currently, Bootstrap’s primary color is defined in SCSS like this:

    $primary: #0d6efd;
    @import "bootstrap/scss/bootstrap";


    However, this approach requires recompilation, and I need a way to change the primary color dynamically via JavaScript or TypeScript.

    What I Have Tried CSS Variables I attempted to override the Bootstrap primary color using CSS variables:

    :root {
    --bs-primary: #ff5733; /* New color */
    }


    But this does not seem to work for all Bootstrap components like buttons and alerts.

    Using JavaScript to Update Variables I also tried updating CSS variables dynamically in TypeScript:

    private changeThemeColor(color: string): void {
    document.documentElement.style.setProperty('--bs-primary', color);
    }


    However, this change does not reflect in Bootstrap components like

    <span class="text-primary">Primary Text</span>
    <button class="btn btn-primary">Primary Button</button>

    Continue reading...

Compartilhe esta Página