Angular Change Detection: OnPush Strategy เพิ่ม Performance

#angular12 เม.ย. 2569

Change Detection คืออะไร

Angular ตรวจสอบการเปลี่ยนแปลงของ data และ update UI ให้อัตโนมัติ กระบวนการนี้เรียกว่า Change Detection

Default Strategy

โดย default Angular จะ check ทุก component ทุกครั้งที่มี event เกิดขึ้น ซึ่งอาจช้าถ้ามี component เยอะ

OnPush Strategy

ด้วย OnPush Angular จะ check เฉพาะเมื่อ

  1. Input reference เปลี่ยน
  2. Event เกิดขึ้นใน component นั้น
  3. Observable ที่ใช้กับ async pipe emit ค่าใหม่
  4. เรียก markForCheck() หรือ detectChanges() เอง
import { ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-user-card',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div>{{ user.name }}</div>
    <div>{{ user.email }}</div>
  `
})
export class UserCardComponent {
  @Input() user!: User;
}

Immutable Data กับ OnPush

// ❌ ผิด - mutate object โดยตรง OnPush จะไม่ detect
this.user.name = 'ใหม่';

// ✅ ถูก - สร้าง object ใหม่
this.user = { ...this.user, name: 'ใหม่' };

ใช้ Signals กับ OnPush

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<p>{{ count() }}</p>`
})
export class CounterComponent {
  count = signal(0);

  increment() {
    this.count.update(v => v + 1);
    // Signal จะ trigger change detection อัตโนมัติ
  }
}

MarkForCheck

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

export class MyComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  updateFromOutside() {
    // บอก Angular ให้ check component นี้
    this.cdr.markForCheck();
  }
}

สรุป

การใช้ OnPush + Immutable data + Signals เป็น best practice สำหรับ Angular performance ควรใช้กับทุก component ที่เป็นไปได้ครับ