2017-05-25 87 views
1

我想添加一些文字showlist.component.html,我showlist.component.ts代码下面给出了,我不知道我该如何使用document.body在角2.请指导如何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); 
    } 

} 
+0

你_can_使用完全一样的。 'document.body'返回'' HTML元素。在你上面的例子中,'document.write(this.myname);'应该用'saurabh'替换所有的主体内容。如果你想引用一个特定的元素,请检查这个[SO帖子](https://stackoverflow.com/a/35209681/3777524) – helllomatt

回答

4

你下面的访问document.body

import { Component, OnInit, Inject } 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(@Inject(DOCUMENT) private document: any) {} 

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

} 
+0

是的确定它是一种先进的东西,但我会尽我所能,'DOCUMENT'是依赖注入(又名DI)令牌,你的组件依赖它来引用Document和非类依赖(因为它不是一个类),我们需要'@Inject'装饰器 –

+0

它的文档在这里https://angular.io/guide/dependency-injection –

+0

'this.document.body.innerHTML = this.myname;',如果我想添加'this.myname'与其他页面数据,那么我需要做什么?上面的行只显示页面上的this.myname并擦除其他所有内容 – user2828442