影响 Angular 中所有组件和模态的主题服务 <ng-template let-modal> 6+

Theme service that affects all components and modals <ng-template let-modal> in Angular 6+

你能帮我保留 theme 服务,并且仍然能够将主题应用到所有组件(以及这些模态框)吗?

结果很长一段时间都没有人回答,所以我决定自己深入研究解决方案,见下文仅供参考。

首先,通过将 Renderer2 放入 theme.service.ts(之前在 header 组件中本地设置)继续使用 theme 服务:

    @Injectable({
      providedIn: 'root'
    })
    export class ThemeService {
      public isDarkMode: boolean;
      private renderer: Renderer2;

      constructor(
        @Inject(DOCUMENT) private document: Document,
        rendererFactory: RendererFactory2
      ) {    this.renderer = rendererFactory.createRenderer(null, null);
      }

      public toggleDarkMode() {
        this.isDarkMode = !this.isDarkMode;

        if (this.isDarkMode) {
          this.renderer.addClass(this.document.body, 'dark-mode');
        } else {
          this.renderer.removeClass(this.document.body, 'dark-mode');
        } 
      }
    }

其次,需要在构造函数中设置一个public变量,这里我选择header.component.ts:

的构造函数
export class HeaderComponent implements OnInit {
      /*
      * Inject the theme service which will be called by our button (click).
      * @param {ThemeService} themeService instance.
      */
      constructor(public themeService: ThemeService) {}

      ngOnInit() {}
    }

然后在 header.component.html 中放置一个按钮来切换主题(注意:您可以将按钮放置在项目的任何位置,以及相应 [=21= 中定义的 public 变量])

<button (click)="themeService.toggleDarkMode()"><i class="fa fa-moon"></i></button>

现在只要单击按钮就会触发 public toggleDarkMode 函数,然后模式和其他组件将在主题服务根据您定义的 dark-mode 样式更新时反映变化,例如:

#lucky.dark-mode {
    color: #a2b9c8;
    background-color: #01263f!important;
}

您可能需要将此应用于 index.html 中的所有 <body>:

<body id="lucky">
  <app-root></app-root>
</body>

祝你好运,编码愉快!