4

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

user386430
  • 4,837
  • 13
  • 41
  • 45
  • https://stackoverflow.com/questions/49886571/angular-2-how-to-select-and-loop-over-multiple-elements-with-the-same-selector, https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll, One of this could help you – sojin Sep 21 '21 at 13:03
  • You need to have this line in ngAfterViewInit, not on ngOnInit..... Also you make sure, there are no *ngIf on the selector elements – Alaksandar Jesus Gene Sep 21 '21 at 13:25

2 Answers2

4
  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

Felipe Chernicharo
  • 3,619
  • 2
  • 24
  • 32
1

I think this answer needs a small update, since the latest way of doing this in Angular 16, following the standalone standard that Angular is heading to, is:

import { DOCUMENT } from '@angular/common';
import { inject } from '@angular/core';

@Component({
  ...
  standalone: true,
  ...
})
class MyComponent {
  private document = inject(DOCUMENT);

  ngOnInit() {
     this.document.<whatever ...>
  }
}
MichaelShake
  • 238
  • 2
  • 13