【问题标题】:Angular 8 - How to remove <style> element from <head> after the component is destroyedAngular 8 - 如何在组件被销毁后从 <head> 中删除 <style> 元素
【发布时间】:2020-05-08 19:29:36
【问题描述】:

Angular - How to remove element from after the component is destroyed

我正在遵循上面的解决方案,但我无法正确显示 css。

当我添加时它返回我 [object module] 而不是 css 内容:

组件.ts

this.styleService.addStyle('usergrid1css', require('../../../assets/css/clr.css'));

html

<style>[object module]</style>

有人可以帮我吗?

提前致谢!

chrome devtools image

code below extracted from the url above

import { Injectable } from '@angular/core';

@Injectable()
export class StyleService {
  private stylesMap: Map<any, Node> = new Map();
  private host: Node;

  constructor() {
    this.host = document.head;
  }

  private createStyleNode(content: string): Node {
    console.log('style');
    const styleEl = document.createElement('style');
    styleEl.textContent = content;
    return styleEl;
  }

  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.ts**


import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { concat, merge, Observable, of, Subject } from 'rxjs';
import { catchError, debounceTime, distinctUntilChanged, switchMap, tap, map } from 'rxjs/operators';

import { StyleService } from '../../services/style.service';

declare function require(name: string): any;
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
 constructor(private fb: FormBuilder,
    private styleService: StyleService) {
  }
ngOnInit() {

    this.styleService.addStyle('usergrid1css', require('./clr.css'));

}

【问题讨论】:

  • 您将需要显示比这两行更多的代码。向我们展示您的 StyleService 代码和使用它的组件代码。
  • require 返回一个模块,而不是文本。您需要从该模块中获取文本,或者找到其他获取 CSS 的方式(例如通过 Ajax)。
  • 这个Demo 与require 配合得很好。 @HereticMonkey
  • 如果您使用的是其他人的代码,在问题中给予他们信任可能是个好主意...我只能告诉您我从您决定分享的代码中看到的和我们一起。
  • @HereticMonkey 是的,但我如何在此处标记它们?

标签: angular angular8


【解决方案1】:

我的回答提出的解决方案是基于github repository of material.angular.io中获得的这个角度服务

我还留下了一个在stackblitz 中运行的示例,说明该服务的使用

服务

import { Injectable } from '@angular/core';

/**
 * Class for managing stylesheets. Stylesheets are loaded into named slots so that they can be
 * removed or changed later.
 */
@Injectable()
export class StyleManagerService {

  /**
   * Set the stylesheet with the specified key.
   */
  setStyle(key: string, href: string) {
    getLinkElementForKey(key).setAttribute('href', href);
  }

  /**
   * Remove the stylesheet with the specified key.
   */
  removeStyle(key: string) {
    const existingLinkElement = getExistingLinkElementByKey(key);
    if (existingLinkElement) {
      document.head.removeChild(existingLinkElement);
    }
  }

}

function getLinkElementForKey(key: string) {
  return getExistingLinkElementByKey(key) || createLinkElementWithKey(key);
}

function getExistingLinkElementByKey(key: string) {
  return document.head.querySelector(`link[rel="stylesheet"].${getClassNameForKey(key)}`);
}

function createLinkElementWithKey(key: string) {
  const linkEl = document.createElement('link');
  linkEl.setAttribute('rel', 'stylesheet');
  linkEl.classList.add(getClassNameForKey(key));
  document.head.appendChild(linkEl);
  return linkEl;
}

function getClassNameForKey(key: string) {
  return `style-manager-${key}`;
}

组件

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
})
export class ExampleComponent implements OnDestroy  {
  themes = [
    'deeppurple-amber',
    'indigo-pink',
    'pink-bluegrey',
    'purple-green'
  ];

  constructor(public _styleManager: StyleManagerService) {
  }

  ngOnDestroy() {
    removeTheme();
  }

  selectTheme(themeName: string) {
    this._styleManager.setStyle('theme', `assets/${themeName}.css`);
  }

  removeTheme() {
    this._styleManager.removeStyle('theme');
  }
}

【讨论】:

猜你喜欢
  • 2018-10-22
  • 1970-01-01
  • 2019-01-28
  • 2014-03-23
  • 2019-07-28
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多