2017-05-25 24 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