Angular: an elementary alternative from Angular 2 onwards
I have an Angular 1 app where I used:
let css = ".toolbar-background {background-color: #D3300E !important;}";
angular.element(document.body).append(angular.element('<div><style>' + css + '</style></div>'));
I am porting my app to Angular 2 and now the object is angular
not available from Angular 2 onward.
It would be really helpful if someone can suggest a possible way to achieve the same in Angular 2.
source to share
There are several ways to do this:
USE OF DOCUMENT
import the document into your component like this:
import {DOCUMENT} from '@angular/platform-browser';
put it into the constructor like this:
constructor(@Inject(DOCUMENT) private document: any) {
}
and use it to add data like this to 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 a working plunker:
https://embed.plnkr.co/lVRcHNJnxgGsD1iwZJll/
USING ElementRef
Import ElementRef and ViewChild into component like this:
import {ViewChild, ElementRef } from '@angular/core';
In the html, point to the div where you want to add data like:
<div #styleDiv></div>
Accessing the div with ViewChild like this:
@ViewChild('styleDiv') styleDiv:ElementRef;
and do the required addition like this:
let css = "h2 {color: green;font-size:14px;}";
let tmp = "<style>" + css + "</style>";
this.styleDiv.nativeElement.insertAdjacentHTML('beforeend',tmp);
Here's a working plunker using ViewChild and ElementRef: https://embed.plnkr.co/lVRcHNJnxgGsD1iwZJll/
source to share