DEV Community

Cover image for Various Ways to Leverage Angular Directives: An In-Depth Guide
Zeeshan Haider Shaheen
Zeeshan Haider Shaheen

Posted on

Various Ways to Leverage Angular Directives: An In-Depth Guide

Angular Directives are a versatile and powerful feature of the Angular framework, enabling developers to modify the DOM and extend its capabilities in creative ways. In this blog, we’ll explore different ways in which Angular Directives can be used to enhance the functionality, aesthetics, and user experience of web applications.

1. Enhancing HTML Elements
Example:Creating Tooltips

Angular Directives can be used to create dynamic tooltips that provide additional information when a user hovers over an element.

ng generate directive tooltip
Enter fullscreen mode Exit fullscreen mode
import { Directive, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appTooltip]'
})
export class TooltipDirective {
  @Input('appTooltip') tooltipText: string;
  tooltipElement = this.renderer.createElement('span');

  constructor(private el: ElementRef, private renderer: Renderer2) {
    this.renderer.listen(this.el.nativeElement, 'mouseover', () => {
      this.showTooltip();
    });
    this.renderer.listen(this.el.nativeElement, 'mouseout', () => {
      this.hideTooltip();
    });
  }

  showTooltip() {
    this.renderer.appendChild(this.el.nativeElement, this.tooltipElement);
    this.renderer.addClass(this.tooltipElement, 'tooltip');
    this.renderer.setProperty(this.tooltipElement, 'textContent', this.tooltipText);
  }

  hideTooltip() {
    this.renderer.removeChild(this.el.nativeElement, this.tooltipElement);
  }
}
Enter fullscreen mode Exit fullscreen mode

2. Styling Elements Dynamically

Example:Changing Background Color

Directives can be used to dynamically change the styling of elements based on user interaction or other conditions.

ng generate directive dynamicStyle
Enter fullscreen mode Exit fullscreen mode
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appDynamicStyle]'
})
export class DynamicStyleDirective {

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

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', 'white');
  }
}
Enter fullscreen mode Exit fullscreen mode

3. Manipulating the DOM Structure

Example:Creating a Collapse/Expand Directive

Directives can modify the structure of the DOM, adding or removing elements dynamically.

ng generate directive collapse
Enter fullscreen mode Exit fullscreen mode
import { Directive, Input, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appCollapse]'
})
export class CollapseDirective {
  @Input() appCollapse: boolean;

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

  @HostListener('click') onClick() {
    this.appCollapse = !this.appCollapse;
    this.toggleCollapse();
  }

  toggleCollapse() {
    const display = this.appCollapse ? 'none' : 'block';
    this.renderer.setStyle(this.el.nativeElement.nextElementSibling, 'display', display);
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Handling Events
Example: Listening to Scroll Events

Directives can be used to listen to events on elements and execute logic based on those events.

ng generate directive scroll
Enter fullscreen mode Exit fullscreen mode

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[appScroll]'
})
export class ScrollDirective {

  @HostListener('window:scroll', ['$event'])
  onScroll(event) {
    console.log('Scrolled', event);
  }
}

Enter fullscreen mode Exit fullscreen mode

5. Implementing Conditional Rendering

Example: If-Else Rendering

Create custom structural directives for conditional rendering of templates.

ng generate directive customIf
Enter fullscreen mode Exit fullscreen mode

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appCustomIf]'
})
export class CustomIfDirective {
  @Input() set appCustomIf(condition: boolean) {
    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { }
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

Angular Directives are a phenomenal tool for developers looking to create dynamic, responsive, and intuitive web applications. They allow for the enhancement of HTML elements, dynamic styling, manipulation of the DOM structure, event handling, and conditional rendering, amongst other things.

By leveraging Angular Directives in creative ways, developers can solve complex problems, reduce code redundancy, and build scalable and maintainable web applications. Whether you are a beginner or an experienced developer, exploring and experimenting with Angular Directives can lead to discovering new and innovative solutions to improve your projects.
Let me know about your thoughts in the comments. Follow me on Twitter @zeeshanhshaheen for more updates.

Top comments (0)