有几个方法可以做到这一点:
在组件这样使用文档
进口单证:
import {DOCUMENT} from '@angular/platform-browser';
像这样在构造函数中注入它:
constructor(@Inject(DOCUMENT) private document: any) {
}
,并用它来将数据追加任何像这样的函数内部:
ngOnInit() {
let css = ".toolbar-background {background-color: #D3300E !important;}";
this.document.body.innerHTML.append = this.document.body.innerHTML + "<div><style>" + css + "</style></div>";
}
这里是工作plunker:
https://embed.plnkr.co/lVRcHNJnxgGsD1iwZJll/
使用ElementRef
导入ElementRef和像这样的组件中的ViewChild:
import {ViewChild, ElementRef } from '@angular/core';
在你的HTML定义要在其中追加像数据的DIV:使用ViewChild这样上面的div
<div #styleDiv></div>
访问:
@ViewChild('styleDiv') styleDiv:ElementRef;
和执行所需的附加像这个:
let css = "h2 {color: green;font-size:14px;}";
let tmp = "<style>" + css + "</style>";
this.styleDiv.nativeElement.insertAdjacentHTML('beforeend',tmp);
这里是使用ViewChild和ElementRef的工作蹲跳者: https://embed.plnkr.co/lVRcHNJnxgGsD1iwZJll/
'Renderer2'? https://angular.io/api/core/Renderer2 – wostex
@wostex我在html中有标记,我想更改类属性。是否有可能与Renderer2做到这一点 –