0

I want the users of my app to have the ability to chose a theme. Therefore I prepared several scss stylesheets which differ in some sort. I now need to load the according stylesheet due to the selected theme. I did not find any working solution on the web nor on stackoverflow.

I tried to build a component for each theme including the according scss in the styleUrls property and using dynamic component loader. I need view encapsulation to set to none. Due to that the styles are not removed if the component gets destroyed. Is there any way to delete styles set by a component with encapsulation set to none?

Or is there any other way to set scss stylesheets dynamically?

Max Solid
  • 1,213
  • 3
  • 21
  • 32
  • Have you tried this https://stackoverflow.com/questions/39643042/load-css-file-dynamically-for-theming ? – Vandesh Dec 10 '17 at 21:12
  • does not work with scss – Max Solid Dec 10 '17 at 21:22
  • Am I right that the style tags for components being destroyed should be removed from head even if ecapsulation is set to none? https://github.com/juleskremer/angular/commit/385ed90ac373c0347ea88fe38685405c01ba1a58 – Max Solid Dec 10 '17 at 21:38

1 Answers1

0

You can use bind to ngClass of a parent component. Example:

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div [ngClass]="theme">
      <form>
        <label for="theme">Choose Your Theme</label>
        <select name="theme" id="theme" (change)="onThemeSelected($event)">
          <option value="theme1">Theme 1</option>
          <option value="theme2">Theme 2</option>
        </select>
      </form>
      <p>Content:</p>
      <ul>
        <li>A</li>
        <li>B</li>
        <li>C</li>
      </ul>
    </div>
  `,
  styles: [``]
})
export class AppComponent {
  theme = 'theme1'

  onThemeSelected(e) {
    this.theme = e.target.value;
  }
}

styles.scss

/* You can add global styles to this file, and also import other style files */

@import './themes/theme1';
@import './themes/theme2';

themes/theme1.scss

.theme1 {
  background: lightblue;
}

themes/theme2.scss

.theme2 {
  background: lightgreen;
}

Source code here: https://github.com/bwhiting2356/angular-themes

Brendan Whiting
  • 494
  • 3
  • 13