如何在角度2中注入document.body

use*_*442 8 javascript angular

我想在showlist.component.html中添加一些文本 ,我的showlist.component.ts代码如下,我不知道如何document.body在角度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);
  }

}
Run Code Online (Sandbox Code Playgroud)

Ham*_*our 19

您执行以下操作来访问 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: any) {}

  ngOnInit() {
this.document.body.innerHTML = this.myname;
  }

}
Run Code Online (Sandbox Code Playgroud)

  • `@angular/platform-b​​rowser` 中的 `DOCUMENT` 已弃用,改为 `@angular/common` (4认同)