Javascript 如何在Angular 2中注入document.body
我想在showlist.component.html中添加一些文本。下面给出了我的代码,我不知道如何在Angular 2中使用Javascript 如何在Angular 2中注入document.body,javascript,angular,Javascript,Angular,我想在showlist.component.html中添加一些文本。下面给出了我的代码,我不知道如何在Angular 2中使用document.body import { Component, OnInit } from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; @Component({ selector: 'app-showlist', templateUrl: './showlist
document.body
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);
}
}
要访问
文档.正文
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;
}
}
你可以像那样使用它
document.body
返回
HTML元素。在上面的例子中,document.write(this.myname)
应将所有正文内容替换为saurabh
。如果你想引用一个特定的元素,请勾选这个是的,当然这是一种高级的东西,但我会尽我所能,DOCUMENT
是依赖注入(aka DI)标记,你的组件依赖它来引用文档和非类依赖(因为它不是类)我们需要@Inject
decoratorthis.document.body.innerHTML=this.myname
,如果我想将this.myname
与其他页面数据一起添加,那么我需要做什么?上面的一行只显示了这一点。我的名字
在页面上,并删除了@angular/platform browser
中的所有其他文档
已被弃用,改为@angular/common
仅供参考:我必须使用我的IDE自动导入:结果如下:从导入{DOCUMENT}“@angular/platform browser/src/dom/dom_tokens”;