Change style programmatically

I need to implement setting page where the final user can select his prefer style of the application.

What is the best solution to implement such a dynamism? Can I change theme variables dynamically?

Do you have a tutorial or example to share with me?

Service for theme

import { Injectable, Inject, Renderer2, RendererFactory2 } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class AppThemeService {

  public renderer: Renderer2;
  public currentTheme;

  constructor(private rendererFactory: RendererFactory2, @Inject(DOCUMENT) private document: Document) 
  {
    this.renderer = this.rendererFactory.createRenderer(null, null);
  }

  activeTheme(item) {
    this.renderer.removeClass(this.document.body, this.currentTheme);
    this.currentTheme = item;
    this.renderer.addClass(this.document.body, item);
  }

}

In variables.scss inside : root{

.theme1 {
    --ion-color-primary: #505151;
    --ion-color-primary-rgb: 80, 81, 81;
    --ion-color-primary-contrast: #ffffff;
    --ion-color-primary-contrast-rgb: 255, 255, 255;
    --ion-color-primary-shade: #505151;
    --ion-color-primary-tint: #505151;
  }
  .theme2 {
    --ion-color-primary: #300948;
    --ion-color-primary-rgb: 80, 81, 81;
    --ion-color-primary-contrast: #ffffff;
    --ion-color-primary-contrast-rgb: 255, 255, 255;
    --ion-color-primary-shade: #300948;
    --ion-color-primary-tint: #300948;
  }

For changing theme add following code in event handler

this.appThemeService.activeTheme(themeName);

For more Ionic tutorials you may visit TechBinomial channel

2 Likes

I really appreciated your help. I don’t understand much but I try to implement the solution