Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 retrieve all elements with class name

Can anyone help with how to find 'All' Elements with a particular class name in Angular 2? I thought it would be trivial but it's giving me more problems that was prepared for.

<span class="classImLookingFor">foo</span> <span class="classImLookingFor">Voo</span> <span class="classImLookingFor">Moo</span> 

I thought by doing what I have below would return all the elements with class "classImLookingFor" but it only returns the first instance.

constructor(private renderer: Renderer){} ngAfterViewInit(){  const el = this.renderer.selectRootElement('.classImLookingFor');  this.renderer.setElementAttribute(el, 'tabindex', 0); } 

Afterwards, my markup looks like this.

<span class="classImLookingFor" tabindex="0">foo</span> <span class="classImLookingFor">Voo</span> <span class="classImLookingFor">Moo</span> 

It seems like I should be able to create a Renderer array, but that doesn't seem to work either. I need to manipulate each element with that class name. Thanks in Advance

like image 846
dekaha1 Avatar asked Apr 12 '17 17:04

dekaha1


People also ask

How do I use elementRef?

To manipulate the DOM using the ElementRef , we need to get the reference to the DOM element in the component/directive. Create a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.

What is Angular element in AngularJS?

The angular. element() Function in AngularJS is used to initialize DOM element or HTML string as an jQuery element. If jQuery is available angular. element can be either used as an alias for the jQuery function or it can be used as a function to wrap the element or string in Angular's jqlite.


2 Answers

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.

like image 69
Paritosh Avatar answered Sep 24 '22 07:09

Paritosh


Angular 10+ document compatibility with SSR, import:

import { DOCUMENT } from '@angular/common' 

then inject:

constructor(@Inject(DOCUMENT) private _document: HTMLDocument) {     } 

And use in your component/ directive like this:

doSomething(): void {  this._document.querySelectorAll('.classImLookingFor') } 
like image 31
Nexeuz Avatar answered Sep 24 '22 07:09

Nexeuz