Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can access DOM element by selector

In Angular2 is there way to get element by it's selector NOT in a template but inside whole DOM?

like image 490
Vnuuk Avatar asked Dec 26 '16 14:12

Vnuuk


3 Answers

It is not recommended to access the DOM directly in angular2, since your are bypassing the Angular2 renderer

You can use other angular 2 features to do that, for example: adding reference to this element.

Check out this issue, it can help you: How to get dom element in angular 2

like image 161
michali Avatar answered Sep 19 '22 10:09

michali


Sure, window.document.querySelector, or window.document.querySelectorAll.

like image 20
Tim Consolazio Avatar answered Sep 21 '22 10:09

Tim Consolazio


Today there is an "Angular" way of using the Document to query for Elements:

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

class DOMService {
  constructor(@Inject(DOCUMENT) private document) {}

  getElementsByClass(clazz: string): HTMLCollection[] {
    return this.document.getElementsByClassName(clazz);
  }
}

Especially with Server-Side rendering Features for example its not recommended to access window directly (window && window.document..). In case you are also manipulating the Elements you should consider using Angulars Renderer2

In case you just need access to an Element inside your current Component you can use @ViewChild or ElementRef features.

like image 30
Tim Avatar answered Sep 19 '22 10:09

Tim