6

Am I getting this wrong or should style nodes disappear from the head of the document when a component is destroyed? https://github.com/juleskremer/angular/commit/385ed90ac373c0347ea88fe38685405c01ba1a58

If I set encapsulation to "none" the style node added for that component remains even if it is destroyed?

Is there a way of deleting the style node when component gets destroyed?

Max Solid
  • 1,213
  • 3
  • 21
  • 32

2 Answers2

6

Angular does not support to removeing style node from document. But I write an Angular Provider named "StyleService" for create/remove a style node from document.

Service: 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);
    }
  }
}

Component: login.component.ts

You need to create a css file in same folder, and require it.

export class LoginComponent implements OnDestroy {

  constructor(
    private styleService: StyleService
  ) {
    styleService.addStyle('loginStyle', require('./style.css'));
  }

  ngOnDestroy(): void {
    this.styleService.removeStyle('loginStyle');
  }
}
Cosmo Dai
  • 335
  • 2
  • 6
1

Here is my opinion on this.

Think that there are 1000 list elements and on click, you are moving to details component for each list element. So if you remove styles on destroying of details component, what if you redirect to it again for other list elements. Every time loading CSS is a burden. Maybe for that reason, it is not getting removed.

Mr_Perfect
  • 8,254
  • 11
  • 35
  • 62