Angular Zoneless: ทำงานโดยไม่ต้องพึ่ง Zone.js
#angular12 เม.ย. 2569
Zoneless Angular คืออะไร
Angular 18 แนะนำ experimental zoneless mode ที่ทำงานโดยไม่ต้องใช้ Zone.js ทำให้ bundle size เล็กลงและ performance ดีขึ้น
เปิดใช้ Zoneless
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideExperimentalZonelessChangeDetection } from '@angular/core';
bootstrapApplication(AppComponent, {
providers: [
provideExperimentalZonelessChangeDetection()
]
});
ลบ Zone.js
// angular.json - ลบ zone.js ออกจาก polyfills
"polyfills": [] // ลบ "zone.js" ออก
ทำงานอย่างไร
ใน zoneless mode Angular จะ detect changes เฉพาะเมื่อ
- Signal เปลี่ยนค่า
- เรียก
markForCheck()หรือdetectChanges() - async pipe emit ค่าใหม่
@Component({
template: `<p>{{ count() }}</p>`
})
export class CounterComponent {
count = signal(0);
increment() {
this.count.update(v => v + 1);
// Angular จะ update UI อัตโนมัติเพราะ signal เปลี่ยน
}
}
ข้อควรระวัง
// ❌ ใน zoneless - setTimeout ไม่ trigger change detection
setTimeout(() => {
this.data = newData; // UI จะไม่ update!
}, 1000);
// ✅ ใช้ signal แทน
setTimeout(() => {
this.data.set(newData); // UI จะ update
}, 1000);
ประโยชน์
- Bundle size เล็กลง ~10-15KB (ไม่มี zone.js)
- Performance ดีขึ้น ไม่มี zone patching
- Debugging ง่ายขึ้น stack trace ชัดเจน
สรุป
Zoneless เป็น experimental ใน Angular 18 แต่จะเป็น default ในอนาคต ควรเริ่มเขียนโค้ดด้วย Signals เพื่อเตรียมพร้อมครับ