Angular2 retrieve all elements with class name

后端 未结 5 1727
[愿得一人]
[愿得一人] 2020-12-16 09:55

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 prepar

相关标签:
5条回答
  • 2020-12-16 10:34

    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')
    }
    
    0 讨论(0)
  • 2020-12-16 10:37

    you need to use DOM in angular

    var element=document.getElementsByClassName("X").item(0);
    

    it works for me!

    0 讨论(0)
  • 2020-12-16 10:41

    This might be a little over-simplistic for your use case, but is there any reason you can't use the native DOM functions, like so?

    var domRepresentation = document.getElementsByClassName('classImLookingFor');
    var angularElement = angular.element(domRepresentation);
    
    0 讨论(0)
  • 2020-12-16 10:45

    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.

    0 讨论(0)
  • 2020-12-16 10:46

    Answering as the comment worked for the OP.

    You should be using

    document.querySelectorAll('.classImLookingFor')
    
    0 讨论(0)
提交回复
热议问题