Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular.element alternative from Angular 2 onwards

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.

like image 647
Suneet Jain Avatar asked Jul 18 '17 11:07

Suneet Jain


People also ask

How do I get ElementRef in angular 8?

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.

Can I use querySelector in angular?

There are three functions on Angular that are best used to manipulate web page elements; these are angular. element , document. getElementById , and querySelector() .

What is ElementRef in angular?

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.

Can I use document getElementById in angular?

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.


1 Answers

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/

like image 197
Fahad Nisar Avatar answered Sep 19 '22 09:09

Fahad Nisar