![](/img/trans.png)
[英]Angular 2 - can I dynamically change the styleUrl in the component?
[英]How to remove style from styleUrl in component Angular 2
忘记您的情况下的封装,它无法帮助您满足您的要求。 相反,使用共享服务,让我们称其为 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.