Create a directive in Angular that adds or removes a class from an element based on its ID or any other attributes.

This directive can listen to a condition or an input to decide whether to add or remove the class. Let’s walk through creating a directive that dynamically adds or removes a class based on an input property, which can be the element’s ID or a condition.

Step 1: Define the Directive

First, you’ll create a directive that takes an input, which could be a boolean or any other type of value that determines whether to add or remove the class. You will also need to handle the element selection within the directive itself.

import { Directive, ElementRef, Input, OnChanges, Renderer2, SimpleChanges } from '@angular/core';

@Directive({
  selector: '[appToggleClass]'
})
export class ToggleClassDirective implements OnChanges {
  @Input() appToggleClass: boolean; // Condition to add or remove class
  @Input() classToToggle: string; // The class to toggle
  @Input() targetElementId: string; // ID of the target element

  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngOnChanges(changes: SimpleChanges): void {
    // Access the element by ID
    const element = this.el.nativeElement.ownerDocument.getElementById(this.targetElementId);

    if (element) {
      if (this.appToggleClass) {
        this.renderer.addClass(element, this.classToToggle);
      } else {
        this.renderer.removeClass(element, this.classToToggle);
      }
    }
  }
}

Step 2: Use the Directive in a Component

Apply the directive to any element, and provide it with the ID of the target element where you want to toggle the class, the class name, and the condition.

<!-- Assume your component HTML looks like this -->
<div id="uniqueElementId">This is the element to be toggled.</div>

<!-- Using the directive -->
<button [appToggleClass]="isActive" classToToggle="highlight" targetElementId="uniqueElementId">
  Toggle Class on Element
</button>

In your component TypeScript file, manage the isActive state:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  isActive: boolean = false;

  toggleClass() {
    this.isActive = !this.isActive;
  }
}

Explanation

  • Directive Logic: The ToggleClassDirective uses Angular’s Renderer2 to safely interact with the DOM, adding or removing a class based on the provided condition (appToggleClass). It listens for changes to its inputs using ngOnChanges, making it reactive to changes in input values.
  • Inputs: The directive accepts three inputs:
  • appToggleClass: The condition under which the class should be added or removed.
  • classToToggle: The class name to add or remove.
  • targetElementId: The ID of the DOM element to which the class should be added or removed.

This setup keeps your Angular components clean and lets the directive handle all the DOM manipulations based on the inputs it receives, adhering to Angular’s design principles of modularity and separation of concerns.

Scroll to Top