【问题标题】:How to implement UI theming with Angular without performance reduction?如何在不降低性能的情况下使用 Angular 实现 UI 主题?
【发布时间】:2018-02-17 16:36:21
【问题描述】:

背景

我有一个 Angular Web 应用程序,其复杂性与 Facebook 非常相似。主要功能之一是视觉定制,这意味着用户可以在运行时更改网站上的每种颜色并将颜色配置保存到他的配置文件中。

我通过使用 NgRx Store 设法实现了这种行为,其中所有颜色都存储并复制到整个应用程序上。颜色通过 Angular [style.property] 表示法分配给每个模板元素。

问题

我注意到,在包含许多项目(大约 500 个)的列表的页面上,CPU 使用率变得很高,并且 UI 开始变慢。

我认为这是因为发出了许多事件,我需要创建 css 悬停效果:

(mouseenter)="$event.target.style.backgroundColor = COLOR_2"
(mouseleave)="$event.target.style.backgroundColor = COLOR_1">

问题

有没有办法消除性能降低或使用其他不会损害性能的主题化方法?

【问题讨论】:

    标签: angular theming


    【解决方案1】:

    您可以创建一个主题指令,而不是为每个组件添加颜色,该指令将在包含theme 类的文档的头部创建一个样式元素。然后,您可以使用此类正确地为所有元素着色。

    import { Directive, Input } from '@angular/core';
    
    @Directive({
      selector: '[appTheme]'
    })
    export class ThemeDirective {
    
      @Input()
      set appTheme(val: string) {
        this.setColor(val);
      }
    
      private themeElement: HTMLStyleElement;
    
      private setColor(color: string) {
        if(!this.themeElement) {
          this.themeElement = document.createElement('style');
          this.themeElement.type = 'text/css';
          document.getElementsByTagName('head')[0].appendChild(this.themeElement);
          document.body.className = 'theme';
        }
        this.themeElement.innerHTML = `.theme { background-color: ${color}; }`;
      }
    }
    

    https://stackblitz.com/edit/angular-azxuvn

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-11
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2021-10-20
      • 2013-10-03
      • 2019-09-25
      相关资源
      最近更新 更多