Angular 2:从组件访问元素,getDocumentById 不起作用 [英] Angular 2: access an element from the Component, getDocumentById doesn't work
问题描述
我有一个 Angular 2 组件,我想在其中检索元素 div
document.getElementById("myId")
,但出现错误:找不到名称文档".我看到在其他帖子中我们可以使用 @ViewChild 做类似的事情,但是我不知道我们如何将它与 div 一起使用,有什么想法吗?你可以通过添加一个 TemplateRef.
模板
组件
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';@成分({选择器:'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent 实现 AfterViewInit {@ViewChild('myId') myId: ElementRef;构造函数(){}ngAfterViewInit() {控制台日志(this.myId.nativeElement);}}
这篇博文 卡拉·埃里克森 (Kara Erickson) 撰写的这本书非常适合熟悉 Angular 执行此类操作的方法.
I have an Angular 2 component where I want to retrieve an element div
<div id ="myId">
by its id. I try doing: document.getElementById("myId")
in my component (TypeScript), but i get an error: "cannot find name document". I see that in other posts we can do something similar using @ViewChild, however I don't see how we can use this with a div, any ideas?
解决方案 You can use @ViewChild with a div by adding a TemplateRef.
Template
<div id ="myId" #myId>
Component
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild('myId') myId: ElementRef;
constructor() {
}
ngAfterViewInit() {
console.log(this.myId.nativeElement);
}
}
This blog post by Kara Erickson is a really good read for getting familiar with the Angular approach to doing things like this.
这篇关于Angular 2:从组件访问元素,getDocumentById 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文