Blog>
Snippets

Attribute Manipulation

Use Renderer2 to set, get, and remove attributes from an HTML element.
// Import Renderer2 from '@angular/core' in Angular component
import { Renderer2 } from '@angular/core';

// Assume renderer is a Renderer2 instance
class MyComponent {
  constructor(private renderer: Renderer2) {}

  // Function to set an attribute
  setAttribute(el: any, attrName: string, attrValue: string) {
    this.renderer.setAttribute(el, attrName, attrValue);
  }

  // Function to get an attribute value
  getAttribute(el: any, attrName: string) {
    return this.renderer.getAttribute(el, attrName);
  }

  // Function to remove an attribute
  removeAttribute(el: any, attrName: string) {
    this.renderer.removeAttribute(el, attrName);
  }
}
This example shows how to use Renderer2 to manipulate attributes of an HTML element in an Angular component. There's a function to set an attribute using setAttribute, another to get an attribute's value using getAttribute, and one more to remove an attribute using removeAttribute.