Sobes.tech
Middle

What directives in Angular do you know? How to create a custom attribute and structural directive?

sobes.tech AI

Answer from AI

In Angular, there are three main types of directives:

  1. Component directives — these are directives with a template, defining UI components.
  2. Attribute directives — modify the appearance or behavior of existing elements.
  3. Structural directives — change the DOM structure by adding or removing elements.

Creating a custom attribute directive

An attribute directive changes the behavior or style of an element. Here's an example of a simple directive that changes the text color:

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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

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

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.removeStyle(this.el.nativeElement, 'color');
  }
}

Usage in template:

<p appHighlight>Hover over me</p>

Creating a custom structural directive

A structural directive modifies the DOM, for example, conditionally displaying elements. Here's an example directive that displays an element if the condition is true:

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

@Directive({
  selector: '[appIf]'
})
export class IfDirective {
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
  ) {}

  @Input() set appIf(condition: boolean) {
    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }
}

Usage:

<div *appIf="isVisible">This block is visible if isVisible is true</div>

Thus, attribute directives influence behavior and style, while structural directives affect the DOM structure.