组件销毁时的angular 5删除样式节点

Max*_*lid 6 styles encapsulation head angular

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

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

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

小智 5

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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

组件: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');
  }
}
Run Code Online (Sandbox Code Playgroud)