Angular CDK: Component Dev Kit สำหรับสร้าง UI ที่ยืดหยุ่น

#angular12 เม.ย. 2569

Angular CDK คืออะไร

Angular CDK (Component Dev Kit) เป็น library ที่ให้ building blocks สำหรับสร้าง UI components โดยไม่มี visual styling ทำให้ยืดหยุ่นกว่า Angular Material

ติดตั้ง

npm install @angular/cdk

Overlay — Popup, Tooltip, Dialog

import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';

@Component({ ... })
export class MyComponent {
  private overlay = inject(Overlay);
  private overlayRef?: OverlayRef;

  openPopup() {
    const positionStrategy = this.overlay.position()
      .global()
      .centerHorizontally()
      .centerVertically();

    this.overlayRef = this.overlay.create({ positionStrategy });
    const portal = new ComponentPortal(PopupComponent);
    this.overlayRef.attach(portal);
  }

  closePopup() {
    this.overlayRef?.dispose();
  }
}

DragDrop

import { DragDropModule, CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

@Component({
  imports: [DragDropModule],
  template: `
    <div cdkDropList (cdkDropListDropped)="drop($event)">
      @for (item of items; track item) {
        <div cdkDrag>{{ item }}</div>
      }
    </div>
  `
})
export class DragListComponent {
  items = ['Angular', 'React', 'Vue', 'Svelte'];

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.items, event.previousIndex, event.currentIndex);
  }
}

Virtual Scrolling

import { ScrollingModule } from '@angular/cdk/scrolling';

@Component({
  imports: [ScrollingModule],
  template: `
    <cdk-virtual-scroll-viewport itemSize="48" style="height:400px">
      @for (item of largeList; track item.id) {
        <div *cdkVirtualFor="let item of largeList">{{ item.name }}</div>
      }
    </cdk-virtual-scroll-viewport>
  `
})

Clipboard

import { Clipboard } from '@angular/cdk/clipboard';

export class MyComponent {
  private clipboard = inject(Clipboard);

  copyText(text: string) {
    this.clipboard.copy(text);
  }
}

สรุป

Angular CDK เหมาะสำหรับสร้าง custom UI components ที่ต้องการ behavior ซับซ้อน เช่น drag-drop, virtual scroll, overlay โดยไม่ต้องเขียนเองตั้งแต่ต้นครับ