I have an Angular 1 application 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 migrating my application to Angular 2 and now the angular
object is not available from Angular 2 onwards.
It will be really helpful if someone can suggest a possible way to achieve the same in Angular 2.
Getting ElementRef in Component Class Create a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.
There are three functions on Angular that are best used to manipulate web page elements; these are angular. element , document. getElementById , and querySelector() .
Angular ElementRef is a wrapper around a native element inside of a View. It's simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object which exposes all the methods and properties of the native elements.
The getElementById method returns the element with the ID Attribute with the specified value. This method is most common in HTML DOM and is used almost every time we manipulate, get info from, or element in our document.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With