Angular Signals คืออะไร และทำไมถึงเปลี่ยนวิธีเขียน Angular ไปตลอดกาล

#angular12 เม.ย. 2569

Angular Signals คืออะไร

Angular 16+ แนะนำ Signals ซึ่งเป็น reactive primitive ใหม่ที่ช่วยให้การจัดการ state ใน Angular ง่ายและ performant ขึ้นมาก

ปัญหาเดิมของ Angular

ก่อนหน้านี้ Angular ใช้ Zone.js ในการ detect การเปลี่ยนแปลงของ state ซึ่งมีปัญหาหลายอย่าง

  • Zone.js patch browser APIs ทั้งหมด ทำให้ overhead สูง
  • Change detection รันทั้ง component tree แม้จะมีการเปลี่ยนแปลงเล็กน้อย
  • Debug ยากเพราะไม่รู้ว่า state เปลี่ยนจากที่ไหน

Signals แก้ปัญหาอย่างไร

Signals เป็น wrapper รอบ value ที่ notify ผู้ที่ subscribe เมื่อค่าเปลี่ยน

import { signal, computed, effect } from '@angular/core';

// สร้าง signal
const count = signal(0);

// อ่านค่า
console.log(count()); // 0

// เปลี่ยนค่า
count.set(1);
count.update(v => v + 1);

// computed signal
const doubled = computed(() => count() * 2);

// effect - รันเมื่อ signal เปลี่ยน
effect(() => {
  console.log('count changed:', count());
});

ใช้ใน Component

@Component({
  template: `
    <p>Count: {{ count() }}</p>
    <button (click)="increment()">+1</button>
  `
})
export class CounterComponent {
  count = signal(0);

  increment() {
    this.count.update(v => v + 1);
  }
}

ข้อดีของ Signals

  1. Fine-grained reactivity — เฉพาะ component ที่ใช้ signal นั้นจะ re-render
  2. ไม่ต้องพึ่ง Zone.js — สามารถ zoneless ได้เลย
  3. Type-safe — TypeScript รู้ type ของ value ใน signal
  4. Interop กับ RxJS — ใช้ toSignal() และ toObservable() แปลงไปมาได้

สรุป

Signals เป็น feature ที่สำคัญที่สุดของ Angular ในรอบหลายปี ถ้าคุณเขียน Angular อยู่ ควรเริ่มใช้ Signals ตั้งแต่วันนี้เลยครับ