Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject document.body in Angular 2

I want to add some text in showlist.component.html. My code is given below, I am not aware how to use document.body in Angular 2.

import { Component, OnInit } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

@Component({
  selector: 'app-showlist',
  templateUrl: './showlist.component.html',
  styleUrls: ['./showlist.component.css']
})
export class ShowlistComponent implements OnInit {

public myname = "saurabh";

  constructor() { }

  ngOnInit() {
//this.myname.appendTo(document.body);
document.body(this.myname);
 //document.write(this.myname);
  }

}
like image 313
user2828442 Avatar asked May 25 '17 20:05

user2828442


People also ask

Can we use document object in angular?

How do you correctly leverage the document object in Angular? import { Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common';@Component({...}) // could be a service too! That's it.

What is $document in Angular JS?

A jQuery or jqLite wrapper for the browser's window.

What is inject in angular?

Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need.


1 Answers

you do the following to access the document.body

import { Component, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-showlist',
  templateUrl: './showlist.component.html',
  styleUrls: ['./showlist.component.css']
})
export class ShowlistComponent implements OnInit {
  public myname = "saurabh";

  constructor(@Inject(DOCUMENT) private document: Document) {}

  ngOnInit() {
    this.document.body.innerHTML = this.myname;
  }
}
like image 110
Hamed Baatour Avatar answered Sep 24 '22 13:09

Hamed Baatour