gpt4 book ai didi

angular 5删除组件销毁上的样式节点

转载 作者:太空狗 更新时间:2023-10-29 17:33:31 28 4
gpt4 key购买 nike

我是不是弄错了,或者当组件被销毁时,样式节点是否应该从文档的头部消失? https://github.com/juleskremer/angular/commit/385ed90ac373c0347ea88fe38685405c01ba1a58

如果我将封装设置为“无”,为该组件添加的样式节点即使被销毁也会保留?

有没有办法在组件被销毁时删除样式节点?

最佳答案

Angular 不支持从文档中删除样式节点。但是我编写了一个名为“StyleService”的 Angular Provider,用于从文档中创建/删除样式节点。

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

组件:login.component.ts

您需要在同一文件夹中创建一个 css 文件,并需要它。

export class LoginComponent implements OnDestroy {

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

ngOnDestroy(): void {
this.styleService.removeStyle('loginStyle');
}
}

关于angular 5删除组件销毁上的样式节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47747984/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com