Angular Directive: สร้าง Custom Directive สำหรับ DOM Manipulation

#angular12 เม.ย. 2569

Directive คืออะไร

Directive ใน Angular มี 3 ประเภท

  1. Component — directive ที่มี template
  2. Structural — เปลี่ยนโครงสร้าง DOM (*ngIf, *ngFor)
  3. Attribute — เปลี่ยน appearance หรือ behavior ของ element

สร้าง Attribute Directive

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

@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {
  @Input() appHighlight = 'yellow';

  constructor(private el: ElementRef) {}

  @HostListener('mouseenter')
  onMouseEnter() {
    this.el.nativeElement.style.backgroundColor = this.appHighlight;
  }

  @HostListener('mouseleave')
  onMouseLeave() {
    this.el.nativeElement.style.backgroundColor = '';
  }
}
<p appHighlight="lightblue">Hover เพื่อ highlight</p>

Structural Directive

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

@Directive({
  selector: '[appIf]',
  standalone: true
})
export class IfDirective {
  @Input() set appIf(condition: boolean) {
    if (condition) {
      this.vcr.createEmbeddedView(this.template);
    } else {
      this.vcr.clear();
    }
  }

  constructor(
    private template: TemplateRef<any>,
    private vcr: ViewContainerRef
  ) {}
}
<div *appIf="isLoggedIn">ยินดีต้อนรับ!</div>

Directive กับ Renderer2

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

@Directive({ selector: '[appBold]', standalone: true })
export class BoldDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    this.renderer.setStyle(this.el.nativeElement, 'font-weight', 'bold');
  }
}

สรุป

Custom Directive ช่วยให้ reuse DOM behavior ได้ง่าย ใช้ Renderer2 แทนการ access DOM โดยตรงเพื่อรองรับ Server-Side Rendering ครับ