board logo
WUICTeam
  • WUICTeam
  • 100% (Exalted)
  • Newbie Topic Starter
2 days ago
Question
I want to change the theme from my own component (for example a "company theme" button). If I call PrimeNG's preset API directly, the colors come out wrong in dark mode until I switch theme a second time. What is the right way to do it?

Answer
Inject ThemeRuntimeService and call apply() with a theme option taken from ThemeCatalogService. Do not call the PrimeNG preset functions yourself.

The reason is the order of operations. When PrimeNG installs a preset it computes the light/dark CSS variables based on whether the theme-dark class is already present. So the class has to be on the document before the preset is applied. apply() does it in the right sequence: it toggles theme-dark on both html and body, then installs the preset, then updates the primary palette, then sets the accessory classes (high contrast, dense). If you reverse the first two steps, dark stays broken until the next theme change.


import { Component, inject } from '@angular/core';
import { ThemeRuntimeService, ThemeCatalogService } from 'wuic-framework-lib';

@Component({ selector: 'app-theme-button', template: '<button (click)="go()">Dark blue</button>' })
export class ThemeButtonComponent {
  private runtime = inject(ThemeRuntimeService);
  private catalog = inject(ThemeCatalogService);

  go() {
    const option = this.catalog.resolve('aura-blue');
    // returns the dark state actually in effect
    const dark = this.runtime.apply(option, { dark: true });
  }
}

Things to know
  • apply() returns the effective dark state: a high-contrast theme or a custom theme with a forced mode imposes its own variant, so do not assume it is the one you asked for.
  • By default the choice is saved in localStorage (wuic-selected-theme and wuic-theme-mode). Pass persist: false for a temporary preview that must not survive a reload.
  • resolve() returns undefined for an unknown value, and apply(undefined) does nothing except reset high contrast, so check the result if the value comes from user input.
  • For dark mode alone, setDark(true) toggles the class without touching the preset.


Documentation: PrimeNG + Dark Themes