[英]How to remove style from styleUrl in component Angular 2
Here is my component这是我的组件
@Component({
selector: 'app-pages-landing',
templateUrl: './pages-landing.component.html',
styleUrls:['../../assets/pages-landing/main.css'],
encapsulation: ViewEncapsulation.None,
})
I import file css of this component by stylesUrls it gen style to head element我通过stylesUrls将这个组件的文件css导入到头元素中
When i change component.当我更改组件时。 This style still remain and next component load style from previous component.
此样式仍然保留,下一个组件会从上一个组件加载样式。 How i can remove it.
我怎样才能删除它。 I want each component have separate style
我希望每个组件都有单独的样式
Forget about encapsulation in your case, it can't help you with your requirement.忘记您的情况下的封装,它无法帮助您满足您的要求。 Instead, use a shared service, let us call it style-service, which will add/remove the style nodes in the document head.
相反,使用共享服务,让我们称其为 style-service,它将添加/删除文档头中的样式节点。
Instead of adding your CSS styles in the stylesUrls of the @ Component decorator, you will add them by using the style-service on ngOnInit function, which will add the style node to the document head.相反,在@组件装饰的stylesUrls添加CSS样式,你将通过使用ngOnInit功能样式的服务,这将风格节点添加到文档头添加。 Once the component gets destroyed on ngOnDestroy function, you will remove the style by using the style-service, which will remove the style node from the document head.
一旦组件在ngOnDestroy函数上被销毁,您将使用 style-service 删除样式,这将从文档头中删除样式节点。
Enough said, lets see some code:话不多说,让我们看一些代码:
style.service.ts 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);
}
}
}
PageLandingComponent页面着陆组件
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.