angular.element alternative from Angular 2 onwards
There are couple of ways to do this:
USING DOCUMENT
import Document in your component like this:
import {DOCUMENT} from '@angular/platform-browser';
inject it in the constructor like this:
constructor(@Inject(DOCUMENT) private document: any) { }
and use it to append the data like this inside any function:
ngOnInit() { let css = ".toolbar-background {background-color: #D3300E !important;}"; this.document.body.innerHTML.append = this.document.body.innerHTML + "<div><style>" + css + "</style></div>"; }
here is the working plunker:
https://embed.plnkr.co/lVRcHNJnxgGsD1iwZJll/
USING ElementRef
Import ElementRef and ViewChild in component like this:
import {ViewChild, ElementRef } from '@angular/core';
In your html define the div in which you want to append data like:
<div #styleDiv></div>
Access above div using ViewChild like this:
@ViewChild('styleDiv') styleDiv:ElementRef;
and perform the required append like this:
let css = "h2 {color: green;font-size:14px;}";let tmp = "<style>" + css + "</style>";this.styleDiv.nativeElement.insertAdjacentHTML('beforeend',tmp);
here is the working plunker using ViewChild and ElementRef: https://embed.plnkr.co/lVRcHNJnxgGsD1iwZJll/
you can use ElementRef and append css.
constructor(myElement: ElementRef) { ... }