角度2:从Component访问元素,getDocumentById不起作用 [英] Angular 2: access an element from the Component, getDocumentById doesn't work
问题描述
我有一个Angular 2组件,我想在其中检索元素div
<div id ="myId">
通过其ID.我尝试在组件(TypeScript)中执行document.getElementById("myId")
,但是出现错误:找不到名称文档".我看到在其他帖子中我们可以使用@ViewChild做类似的事情,但是我看不到如何将它与div结合使用,有什么主意吗?
您可以通过添加 组件 此博客文章卡拉·埃里克森(Karl Erickson)撰写的一本非常好的书,因为它熟悉Angular的方法来完成这种事情. I have an Angular 2 component where I want to retrieve an element div
You can use @ViewChild with a div by adding a TemplateRef. Template Component This blog post by Kara Erickson is a really good read for getting familiar with the Angular approach to doing things like this. 这篇关于角度2:从Component访问元素,getDocumentById不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 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);
}
}
<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? <div id ="myId" #myId>
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);
}
}