In Angular2 is there way to get element by it's selector NOT in a template but inside whole DOM?
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
Sure, window.document.querySelector
, or window.document.querySelectorAll
.
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.
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