21

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);
  }

}
halfer
  • 19,824
  • 17
  • 99
  • 186
user2828442
  • 2,415
  • 7
  • 57
  • 105
  • You _can_ use it exactly like that. `document.body` returns the `` HTML element. In your case above, `document.write(this.myname);` should replace all the body contents with `saurabh`. If you want to reference a specific element, check this [SO post](https://stackoverflow.com/a/35209681/3777524) – helllomatt May 25 '17 at 20:22

1 Answers1

42

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;
  }
}
Splaktar
  • 5,506
  • 5
  • 43
  • 74
Hamed Baatour
  • 6,664
  • 3
  • 35
  • 47
  • 1
    Yeah sure it's kind advanced stuff but I will try my best, `DOCUMENT` is dependency injection(aka DI) token that your component depend on it to refer to the Document and for non-class dependencies (as it's not a class) we need the `@Inject` decorator – Hamed Baatour May 25 '17 at 20:46
  • `this.document.body.innerHTML = this.myname;` , if i want to add `this.myname` with other page data, then what i need to do ? The above line is only showing `this.myname` on the page and erasing everything else – user2828442 Jan 26 '18 at 12:20
  • 4
    `DOCUMENT` in `@angular/platform-browser` is deprecated, changing to `@angular/common` – Jos May 02 '18 at 10:19
  • FYI: I had to automatically import using my IDE: it came up as this: import { DOCUMENT } from "@angular/platform-browser/src/dom/dom_tokens"; – simbro Jul 09 '18 at 10:44