如何更改 Angular 10 中的 body 标签类(最佳实践)?

Tel*_*mon 6 html css angular angular10

我想在 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');
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Phi*_*hix 11

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

虽然“正确的方式”是主观的,但您可以通过一些选择使其成为“Angular”

成分:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<p>
  Current theme: {{ currentTheme }}

  <button (click)="switchTheme('light')">Light mode</button>
  <button (click)="switchTheme('dark')">Dark mode</button>
</p>
Run Code Online (Sandbox Code Playgroud)

执行此操作的方法有很多,但定义类型的一个好处是如果您提供了错误的值,例如:

<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>
Run Code Online (Sandbox Code Playgroud)

你会得到一个错误:

“noop”类型的参数不可分配给“Theme”类型的参数。

堆栈闪电战