Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get document object in angular component

Tags:

angular

can anybody tell how to get document object angular. I have tried with ElementRef. It is not working

let elements = this.elem.nativeElement.querySelectorAll('.classImLookingFor');

Can anybody suggest how to get querySelectorAll in component in angular?

Thanks

like image 957
user386430 Avatar asked Oct 13 '25 09:10

user386430


1 Answers

  1. import Inject from @angular/core and DOCUMENT from @angular/common
import { Component, Inject, ... } from '@angular/core';
import { DOCUMENT } from '@angular/common';
  1. Inject the DOCUMENT interface inside your class' constructor like this:
export class MyComponent {

    // ...

constructor(@Inject(DOCUMENT) private document: Document) {}
  1. Now you can use the document object inside your class methods. Intellisense will display all the methods and properties of the Document interface, such as querySelector, getElementById, addEventListener etc..
myMethod() {
   this.document.<whatever ...>

   // ...
}

enter image description here

like image 109
Felipe Chernicharo Avatar answered Oct 15 '25 15:10

Felipe Chernicharo