Find an element by ID in Angular 17

Find an element by ID in Angular 17

Here is a step-by-step tutorial on how to find an element by ID in Angular 17:

Step 1: Import the ElementRef class

The ElementRef class is a dependency injection token that provides access to the DOM element corresponding to an Angular component or directive. To use it, you need to import it into your component's constructor.

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

Step 2: Inject the ElementRef into your component

In the constructor of your component, you can inject the ElementRef into your component's constructor using the dependency injection system.

constructor(private elementRef: ElementRef<HTMLElement>) {}

Step 3: Get the native element reference

The ElementRef provides a nativeElement property that gives you access to the underlying DOM element. You can use this property to get the ID of the element.

const elementId = this.elementRef.nativeElement.id;

Step 4: Find the element by ID

You can use the getElementById() method to find the element in the DOM by its ID.

const element = document.getElementById(elementId);

Step 5: Access the element's properties and methods

Once you have a reference to the element, you can access its properties and methods. For example, you can get the element's content using the textContent property.

const elementContent = element.textContent;

Here is an example of how to find an element by ID and change its content:

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

@Component({
  selector: 'app-root',
  template: `
    <div id="my-element">Hello, world!</div>
  `,
})
export class AppComponent {
  constructor(private elementRef: ElementRef<HTMLElement>) {}

  ngOnInit() {
    const element = document.getElementById('my-element');
    element.textContent = 'This is new content.';
  }
}

This code will find the element with the ID my-element and change its content to This is new content.


  • Date: