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?
Add a template reference variable to the component HTML element. Import @ViewChild decorator from @angular/core in component ts file. Use ViewChild decorator to access template reference variable inside the component.
The getElementById method returns the element with the ID Attribute with the specified value. This method is most common in HTML DOM and is used almost every time we manipulate, get info from, or element in our document.08-Dec-2021.
Getting ElementRef in Component ClassCreate a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With