如何在角度10中更改身体标签类别-最佳实践

时间:2020-08-12 23:21:50

标签: html css angular angular10

我想在TAG Body的两个类别(亮和暗)之间切换。

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

 User::AgentSearch($this->search)->paginate(20);

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

谢谢!

1 个答案:

答案 0 :(得分: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

相关问题