【发布时间】: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>
有人可以帮我吗?
提前致谢!
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 是的,但我如何在此处标记它们?