有幾個方法可以做到這一點:
在組件這樣使用文檔
進口單證:
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做到這一點 –