Home > Software design >  Check elementById inside a particular div/Angular Component
Check elementById inside a particular div/Angular Component

Time:09-22

Actually I was looking a way of getting DOM Element inside a component, like right now , I am using document.getElementByID() to get the reference of that particular element and it returns the first element in the whole document that matches the id.

But I want that it should return the first matching element from the html of that particular component.

Or is there any other way to do that?

CodePudding user response:

Ideally you should avoid querying the dom directly using the DOM API methods. Though it works, it is not recommended to query the entire DOM, when you know that you just have to get the element from your component.

There are various ways of obtaining reference to an element inside component, the most common way is using the ViewChild decorator:

Let's say you want to access, span element, use # also known as template reference variable to mark this element, like this:

 <span #templateRef>I am span</span> 

Now, in your component, you can reference this element like this:

@ViewChild("tref", {read: ElementRef}) tref: ElementRef;

 ngAfterViewInit(): void {
      // outputs `I am span`
      console.log(this.templateRef.nativeElement.textContent);
 }  

CodePudding user response:

I added templateRef to the whole div in the component and used this.templateRef.nativeElement.querySelector(`#id`);

  • Related