Sobes.tech
Middle+

What features have you used regarding custom directives in your experience?

sobes.tech AI

Answer from AI

Custom directives allow you to abstract repetitive logic and DOM manipulations.

Features of usage:

  • Reusability: Creating reusable behavior components.
  • DOM manipulation: Direct access to the element and its content.
  • Data interaction: Using input properties (inputs) to pass data into the directive and output properties (outputs) to trigger events.
  • Lifecycle hooks: Using lifecycle hooks (e.g., ngOnInit, ngOnDestroy) to manage behavior.
  • Structural directives: Changing the DOM structure (e.g., ngIf, ngFor).

Example of a structural directive that shows content based on a condition:

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

@Directive({ selector: '[appShowIf]'})
export class ShowIfDirective {

  constructor(
    private templateRef: TemplateRef<any>, // Reference to the element the directive is applied to
    private viewContainer: ViewContainerRef // Container for embedding templates
  ) { }

  @Input() set appShowIf(condition: boolean) {
    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef); // Show element
    } else {
      this.viewContainer.clear(); // Hide element
    }
  }
}

Attribute directives for changing appearance or behavior of an element.

Example of an attribute directive that changes background color on hover:

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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  @Input('appHighlight') highlightColor: string; // Input property

  constructor(private el: ElementRef) { }

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.highlightColor || 'yellow'); // Apply color on hover
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null); // Reset color on mouse leave
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

Comparison of custom directives with components:

Feature Directive Component
Template No own template Has its own template and styles
Selector Attribute ([appDirective]) or class Element (<app-component>)
DOM manipulation Direct access to the host element Manages DOM inside its own template
Reusability Behavior for existing elements Creating new UI elements

Use directives to add behavior to existing elements, validate forms, work with animations, or handle specific events. Use components to create standalone, reusable UI blocks.