如何在 Angular 10 中更改正文标签 class(最佳实践)?

How can I change a body tag class in Angular 10 (best practice)?

我想在 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');
  }
}

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

编辑:向 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>

你会得到一个错误:

Argument of type '"noop"' is not assignable to parameter of type 'Theme'.

StackBlitz