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?
Asked
Active
Viewed 8.3k times
36

joeCarpenter
- 1,495
- 4
- 19
- 32
-
Can you show your code – Gab Mar 04 '17 at 03:55
2 Answers
71
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.

JayChase
- 11,174
- 2
- 43
- 52
-
18
-
using the index property you can add an indexed template reference variable to elements created with *ngFor – user2713706 Jun 25 '18 at 01:04
-
1but then you would have to dynamically generate the @ViewChild(...) annotations too, which is not possible. What if you do not know the length of the *ngFor list? – Adam Bajger Dec 14 '18 at 15:36
15
Add Template Reference variable to the element you need access to:
<div #myDiv></div>
And in the component:
class MyComponent implements AfterViewInit {
@ViewChild('myDiv') myDiv: ElementRef;
constructor() {}
ngAfterViewInit() {
console.log(this.myDiv);
}
}

seidme
- 12,543
- 5
- 36
- 40
-
24
-
@MarcinKapusta using ids is not recommended since in a platform like angular it's hard to avoid name collisions (if you have a lot of components). In what case will id be generated dynamically? The all point of identifiers is to be unique and expected. – Shachar Har-Shuv Jan 16 '19 at 20:32