How to style Angular component dynamically

47 views Asked by At

I am working on an Angular project's themes. My aim is to implement a sustainable light, dark mode into the project. As you already know, The light mode has it's own styles and so the dark.

To carry this out, I created a services which contains: a boolean darkMode (if true this indicate that darkMode is enabled, false means disabled), two local storage functions(to get and set the darkMode value)

import { Injectable } from '@angular/core';
Import {localStorage} from... 

@Injectable({
  providedIn: 'root',
})

export class ThemeDataService {

  constructor(private local:localStorage) { }

  darkMode:boolean=false

  getdarkMode(): string {
    return local.get...
  }

  SetdarkMode(darkmode): boolean {
    return local.get...
  }
}

Then in my components, I fetched the data from the localStorage and make the verications in order to render true to a boolean Var if the value is true on the other hand false(as the localStorage returns values in string format)

import { Component } from '@angular/core';
import { MyService } from './my-service.service';

@Component({
  selector: 'app-my-component',

  templateUrls:... 
  StyleUrls:'[... ] ' 
})

export class ThemeDataService {
  darkMode: boolean;

  constructor(private theme: ThemeDataService) {

    this.darkMode =      (this.theme.getdarkMode() == 'true' ) ? true : false ;
  }
}

Concerning the styling I used [ngStyle] to style the components dynamically as the styles are essentially background-colors and colors.

Now the problem is that I also have some angular mat-field I need to customize, to customize those mat-field I must select some css classes(those classes does not directly exist in the .html file where the mat-form structure is used).

How could I apply those classes css styles if the darkMode:boolean is true?

1

There are 1 answers

0
Moman Raza On

Create a service to manage the application's theme state.

    // theme.service.ts
    import { Injectable } from '@angular/core';
    @Injectable({
      providedIn: 'root'

   })

    export class ThemeService {
      private currentTheme: string = 'light';
    
      constructor() {}
    
      getCurrentTheme(): string {
        return this.currentTheme;
      }
    
      setTheme(theme: string): void {
        this.currentTheme = theme;
        // You might want to save the current theme preference to local storage
        // to persist it across page reloads.
        localStorage.setItem('theme', theme);
      }
    }

Theme Switching Logic

// app.component.ts
import { Component, OnInit } from '@angular/core';
import { ThemeService } from './theme.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private themeService: ThemeService) {}

  ngOnInit(): void {
    // Check if there's a theme preference saved in local storage
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      this.themeService.setTheme(savedTheme);
    }
  }

  toggleTheme(): void {
    const currentTheme = this.themeService.getCurrentTheme();
    const newTheme = currentTheme === 'light' ? 'dark' : 'light';
    this.themeService.setTheme(newTheme);
  }
}

In your HTML template, you can bind the theme toggling logic to a button or any UI element:

<!-- app.component.html -->
<button (click)="toggleTheme()">Toggle Theme</button>

Finally, in your root component (usually app.component.html), dynamically load the appropriate CSS file based on the current theme:

<!-- app.component.html -->
<link rel="stylesheet" [href]="'styles-' + themeService.getCurrentTheme() + '.css'">