繁体   English   中英

如何从组件 Angular 2 中的 styleUrl 中删除样式

[英]How to remove style from styleUrl in component Angular 2

这是我的组件

@Component({
selector: 'app-pages-landing',
templateUrl: './pages-landing.component.html',
styleUrls:['../../assets/pages-landing/main.css'],
encapsulation: ViewEncapsulation.None,
})

我通过stylesUrls将这个组件的文件css导入到头元素中在此处输入图片说明

当我更改组件时。 此样式仍然保留,下一个组件会从上一个组件加载样式。 我怎样才能删除它。 我希望每个组件都有单独的样式

忘记您的情况下的封装,它无法帮助您满足您的要求。 相反,使用共享服务,让我们称其为 style-service,它将添加/删除文档头中的样式节点。

相反,在@组件装饰的stylesUrls添加CSS样式,你将通过使用ngOnInit功能样式的服务,这将风格节点添加到文档头添加。 一旦组件在ngOnDestroy函数上被销毁,您将使用 style-service 删除样式,这将从文档头中删除样式节点。

话不多说,让我们看一些代码:

style.service.ts

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 {
    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);
    }
  }
}

页面着陆组件

import { Component, OnInit, OnDestroy} from '@angular/core';

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

declare const require: any;

@Component({
  selector: 'app-pages-landing',
  templateUrl: './pages-landing.component.html',
  styleUrls:[],//remove CSS from here
})
export class PageLandingComponent implements OnInit, OnDestroy {

  constructor(private styleService: StyleService) { }

  ngOnInit() {
    this.styleService.addStyle('main', require('../../assets/pages-landing/main.css'));
  }

  ngOnDestroy() {
    this.styleService.removeStyle('main');
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM