Angular2 retrieve all elements with class name

Doesn’t this return all the elements in the DOM? Is there a way how to return only elements generated by the Angular component I’m “in”?

You need to…

  1. Inject ElementRef in the constructor

    constructor(private renderer: Renderer, private elem: ElementRef){}
    
  2. Find the elements you are searching using querySelectorAll api.

    ngAfterViewInit(){
        // you'll get your through 'elements' below code
        let elements = this.elem.nativeElement.querySelectorAll('.classImLookingFor');
    }
    

The answer @Aravind has provided is not the best for the performance as it will search the whole DOM.

This solution will just search the DOM inside the current component.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)