1

我想在 TAG Body 的两个课程(浅色和深色)之间切换。

我做了什么?我创建了一个服务:

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

@Injectable({
  providedIn: 'root'
})
export class ThemeService {
  body = document.body;

  constructor() { }

  changeLight() {
    this.body.classList.replace('light', 'dark');
  }

  changeDark() {
    this.body.classList.replace('dark', 'light');
  }
}

它按预期工作,但我知道这段代码没有使用最佳实践。
在这两个类之间进行更改的正确方法是什么?

4

1 回答 1

2

编辑:向 stackblitz 添加了一项服务,但同样,有很多方法可以做到这一点。这只是一个起点。

虽然“正确的方式”是主观的,但您可以选择使其“Angular-y”

零件:

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

// Create a type that accepts either the string 'light' or 'dark' only
type Theme = 'light' | 'dark';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  // Default to 'light' theme
  currentTheme: Theme = 'light';

  // Inject document which is safe when used with server-side rendering
  constructor(@Inject(DOCUMENT) private document: Document) {
    // Add the current (light) theme as a default
    this.document.body.classList.add(this.currentTheme);
  }

  // Swap them out, and keep track of the new theme
  switchTheme(newTheme: Theme): void {
    this.document.body.classList.replace(this.currentTheme, newTheme)
    this.currentTheme = newTheme;
  }
}

HTML:

<p>
  Current theme: {{ currentTheme }}

  <button (click)="switchTheme('light')">Light mode</button>
  <button (click)="switchTheme('dark')">Dark mode</button>
</p>

有很多方法可以做到这一点,但定义类型的一个好处是如果您提供了错误的值,例如:

<p>
  Current theme: {{ currentTheme }}

  <button (click)="switchTheme('light')">Light mode</button>
  <button (click)="switchTheme('dark')">Dark mode</button>
  <button (click)="switchTheme('noop')">Invalid</button>
</p>

你会得到一个错误:

'"noop"' 类型的参数不能分配给 'Theme' 类型的参数。

StackBlitz

于 2020-08-12T23:59:05.590 回答