Ionic primary color dynamically change

2019-03-02 11:27发布

Is there a way to make a separate theme, for example called BlueTheme, where I change the $colors primary, secondary, danger etc.. variables when the theme is activated? Or do I have to manually change the classes and locations where these colors are applied? e.g.

.BlueTheme {
//Whenever this theme is activated, I want to change the primary, secondary colors etc
     $colors {
         primary: different color,
         secondary: another color, etc...
     }
}

Thanks!

1条回答
Fickle 薄情
2楼-- · 2019-03-02 12:08

Here are notes I took from this Youtube video, for my own future use.

service

import {Injectable} from '@angular/core';
import {BehaviourSubject} from 'rxjs/Rx';

@Injectable
export class

     SettingsProvider {
      private theme: BehaviorSubject<String>;

      constructor (
        this.theme = new BehaviorSubject('dark-theme');
       }
       setActiveTheme(val) {
         this.theme.next(val)
       }

       getActiveTheme()  {
          return this.theme.asObservable();
       }

}

/theme/variables.scss

// immediately after
@import "ionic.globals";

@import "custom-theme-light;
@import "custom-theme-dark";

/theme/custom-theme-light.scss

.light-theme {
   ion-content {
     background-color: fff;
     color:000;
   }
   .header .toolbar-title {
    color: #000;
   }
   .header .tooblar-background {
     border-color: #EFF;
     background-color: #fff;
   }
   .tab-button {
     background-color: #fff;
   }
}

theme/custom-theme-dark.scss

.dark-theme {
   ion-content {
     background-color: #000;
     color: #FFF;
   }
   .header .toolbar-title {
    color: #FFF;
   }
   .header .tooblar-background {
     border-color: #100;
     background-color: #000;
   }
   .tab-button {
     background-color: #000;
   }
}

home.html

inside ion-header > ion-navbar after ion-title

<ion-buttons end>
  <button ion-button icon-only (click)="toggleAppTheme()">
    <ion-icon name="bulb"></ion-icon>
  </button>
</ion-buttons>

home.ts

export HomePage {
  selectedTheme: string;
  constructor(settings: SettingsProvider) {
     this.settings.getTheme().subscribe(theme => this.selectedTheme = theme);
   }

  toggleAppTheme() {
    if (this.selectedTheme === 'dark-theme') {
      this.settings.setActiveTheme('light-theme');
    } else {
      this.settings.setActiveTheme('dark-theme');
    }
  }

}

app-component.ts

export class MyApp {
  //after rootPage
  selecteTheme: string

  constructor( ..., private settings: Settings)
    this.settings.getTheme().subscribe(theme => this.selectedTheme = theme);
    // above platform.ready

app.html

<ion-nav [root]="rootPage" [class]="selectedTheme"></ion-nav>

variables.scss

//inside $colors (); add

dark-theme-primary:
light-theme-primary;

inside html template

[color]="selectedTheme + '-primary'"
查看更多
登录 后发表回答