Search code examples
htmlangularcss-selectorsangular5angular2-services

How can I find an element by css selector in Angular2 (ngx)?


How can I find an element by css selector in whole document, not only in child elements in Angular2 (ngx)?


Solution

  • first you will need to import the ElementRef from angular core, then you can use the query selector method to get the element

    import { ElementRef,OnInit} from '@angular/core';
         element;
    
    constructor( private el: ElementRef) {}
    ngOnInit() {
        this.HTMLElement: HTMLImageElement = this.el.nativeElement.querySelector(`#selector`);
      }
    

    checkout these documentation on ElementRef and HTMLElement

    Caution from the angular documentation

    Use this API as the last resort when direct access to DOM is needed. Use templating and data-binding provided by Angular instead. Alternatively you can take a look at Renderer2 which provides API that can safely be used even when direct access to native elements is not supported.

    Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker.