简体   繁体   中英

Get Element Reference of a DOM Element created dynamically from a library

I want to add a class to a DOM Element by taking it's reference. But the element is created by a library and I cannot access it directly, means I can't use ViewChild or HostBinding on that DOM Element.

I can access it directly using document.querySelector(<.classname>) and then add another class to it. But it is Javascript, right? Is there any way to do it in Angular? How to do DOM Manipulation for a dynamically created DOM Element not having an id or #reference?

I want to add a class "hidden" to image layer element of Openlayers. I am using the above method but how to do it in angular?

You can use ElementRef . Simply inject ElementRef in your component and you can select the DOM element you want using its class. Im am assuming that the element that you are looking for already has another class which you can refer to. Here is an example implementation:

import {ElementRef} from '@angular/core';

export class MyClassComponent {

   constructor(private: elRef: ElementRef) {
   
      findMyElement(): void { 
         console.log(this.elRef.nativeElement.querySelector('.myclass'));
      }
   }
}

Please note that, querySelector will find the first occurrence of this element. Therefore, you have to use it with caution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM