Angular Dark Theme

问题描述 投票:0回答:1

您好,我制作了一个切换按钮,将我的Ionic 3应用程序更改为黑暗模式。但是我不知道在哪里定义全局类[class.dark-theme] =“ dark”。必须在app.component.ts上才能对整个应用程序进行更改。这是我到目前为止所拥有的

any-page.html

<ion-item>
    <ion-label>
      Dark Mode
    </ion-label>
    <ion-toggle [(ngModel)]="dark"></ion-toggle>
  </ion-item>

variable.scss

.dark-theme
{
  ion-label{
    font-size: 33pt;
  }
}

app.component.ts

export class MyApp {
  dark=false;
}

我应该如何为NgModel =“ dark”([class.dark-theme] =“ dark”)定义类

angular ionic-framework
1个回答
0
投票
首先,创建一个组件dark-mode.component:

import { DOCUMENT } from '@angular/common'; export class DarkModeComponent implements OnInit { private class = 'dark'; private storage = 'darkMode'; @Input() get value(): boolean { return this.document.body.classList.contains(this.class); } set value(isDark: boolean) { localStorage.setItem(this.storage, isDark.toString()); if (isDark) { this.document.body.classList.add(this.class); } else { this.document.body.classList.remove(this.class); } } constructor(@Inject(DOCUMENT) private document: Document) { } ngOnInit() { const value = localStorage.getItem(this.storage); if (value) { this.value = JSON.parse(value); } } }

我正在使用本地存储来保留用户的选择。这是HTML(太复杂了):

<span (click)="value = !value">Switch theme</span>

我已将此组件导入到我的app.module.ts中:

@NgModule({
  declarations: [
    AppComponent,
    ...
    DarkModeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MaterialModule,
    ...
  ],
  providers: [...],
  bootstrap: [AppComponent],
})
export class AppModule { }

然后您只需要在HTML模板中调用组件,我将其放入menu.component.html:

<dark-mode></dark-mode>

我希望它会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.