【问题标题】:angular 5 removing style node on component destroyangular 5删除组件销毁上的样式节点
【发布时间】:2017-12-11 07:12:51
【问题描述】:

我是不是弄错了,或者当组件被销毁时样式节点是否应该从文档头部消失? https://github.com/juleskremer/angular/commit/385ed90ac373c0347ea88fe38685405c01ba1a58

如果我将封装设置为“无”,为该组件添加的样式节点即使被销毁也会保留?

有没有办法在组件被销毁时删除样式节点?

【问题讨论】:

    标签: angular styles encapsulation head


    【解决方案1】:

    Angular 不支持从文档中移除样式节点。但是我编写了一个名为“StyleService”的Angular Provider,用于从文档中创建/删除样式节点。

    服务:style.service.ts

    import { Injectable, Inject, Optional } from '@angular/core';
    
    import { STYLE_HOST } from 'app/common';
    
    @Injectable()
    export class StyleService {
    
      private stylesMap: Map<any, Node> = new Map();
    
      constructor(
        @Optional() @Inject(STYLE_HOST) private host: Node
      ) {
        if (host === null) {
          this.host = document.head;
        }
      }
    
      createStyleNode(content: string): Node {
        const styleEl = document.createElement('style');
        styleEl.textContent = content;
        return styleEl;
      }
    
      has(key: any): boolean {
        return this.stylesMap.has(key);
      }
    
      addStyle(key: any, style: string): void {
        const styleEl = this.createStyleNode(style);
        this.stylesMap.set(key, styleEl);
        this.host.appendChild(styleEl);
      }
    
      removeStyle(key: any): void {
        const styleEl = this.stylesMap.get(key);
        if (styleEl) {
          this.stylesMap.delete(key);
          this.host.removeChild(styleEl);
        }
      }
    }
    

    组件:login.component.ts

    你需要在同一个文件夹中创建一个 css 文件,并且需要它。

    export class LoginComponent implements OnDestroy {
    
      constructor(
        private styleService: StyleService
      ) {
        styleService.addStyle('loginStyle', require('./style.css'));
      }
    
      ngOnDestroy(): void {
        this.styleService.removeStyle('loginStyle');
      }
    }
    

    【讨论】:

    • 效果很好。我只会将文档引用更改为 Angular 的文档引用,以允许它在服务器上运行: import { DOCUMENT } from '@angular/common';
    • 我还必须将需求更改为导入
    【解决方案2】:

    这是我对此的看法。

    假设有 1000 个列表元素,点击后,您将移动到每个列表元素的详细信息组件。因此,如果您在销毁详细信息组件时删除样式,如果您再次重定向到其他列表元素会怎样。每次加载 CSS 都是一种负担。也许出于这个原因,它没有被删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 2019-07-28
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 2018-10-22
      • 2015-06-08
      相关资源
      最近更新 更多