【问题标题】:How can I change a body tag class in Angular 10 (best practice)?如何更改 Angular 10 中的 body 标签类(最佳实践)?
【发布时间】:2020-12-02 18:10:15
【问题描述】:

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

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

【问题讨论】:

  • 如果您不知道最佳做法是什么,您怎么知道这不是最佳做法?
  • 看到 body 标签将在您的 Angular 应用程序之外,这是您必须这样做的方式。
  • @RobertHarvey 我知道@ViewChild() 是获取元素的最佳做法,但我没有让它工作。
  • 主体不是任何组件的子组件。
  • @AdrianBrand 是的,你是对的!我正在尝试使用指令而不是服务。

标签: html css angular angular10


【解决方案1】:

编辑:向 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”类型的参数不能分配给“主题”类型的参数。

StackBlitz

【讨论】:

  • 非常感谢您的回答。
猜你喜欢
  • 1970-01-01
  • 2017-01-30
  • 2012-10-13
  • 1970-01-01
  • 2021-07-05
  • 1970-01-01
  • 2011-03-26
  • 2010-09-27
  • 1970-01-01
相关资源
最近更新 更多