Directives พื้นฐาน: *ngIf, *ngFor, ngClass, ngStyle

Directive คือคำสั่งที่เพิ่มพฤติกรรมให้ Element ใน Template โดย Angular มี Directive พื้นฐานสำหรับควบคุมการแสดงผล การวนรายการ และการเปลี่ยน Class/Style ตามข้อมูล

Timeline/ประวัติศาสตร์

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
  subgraph Era1["ยุคซ่อนด้วย CSS / CSS Toggle"]
    A["display:none
ซ่อนด้วย style"] end subgraph Era2["ยุค Template Logic / Angular Directives"] B["*ngIf
เพิ่ม/ลบ Element"] C["*ngFor
แสดงรายการ"] end subgraph Era3["ยุค UI State / State Driven UI"] D["ngClass/ngStyle
เปลี่ยนหน้าตาตามสถานะ"] E["trackBy
เพิ่มประสิทธิภาพ"] end A --> B --> C --> D --> E

Directive สำคัญ

ตารางเปรียบเทียบ Directive

Directive ประเภท หน้าที่ ตัวอย่าง
*ngIf Structural เพิ่ม/ลบ Element แสดงเมื่อ login
*ngFor Structural วนรายการ แสดงรายการสินค้า
ngClass Attribute เปลี่ยน class active/disabled
ngStyle Attribute เปลี่ยน style สีหรือขนาดตัวอักษร
ng-template Template เก็บ Template สำรอง loading state
ng-container Helper ครอบ logic ไม่เพิ่ม DOM group condition

Mermaid Diagram: Directive Decision

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart TD
  A["ต้องควบคุม Template?
Need template control?"] --> B{"เงื่อนไขเดียว?
Single condition?"} B -->|ใช่ / Yes| C["ใช้ *ngIf
Conditional render"] B -->|ไม่ใช่ / No| D{"เป็นรายการ?
List?"} D -->|ใช่ / Yes| E["ใช้ *ngFor + trackBy
List render"] D -->|ไม่ใช่ / No| F["ใช้ ngClass/ngStyle
Visual state"]

สมการคณิตศาสตร์: ประสิทธิภาพของ trackBy

R = N - K

Code Example

// course-list.component.ts
// Component สำหรับแสดงรายการบทเรียนและใช้ Directives
import { Component } from '@angular/core';

interface Lesson {
  id: number;
  title: string;
  completed: boolean;
}

@Component({
  selector: 'app-course-list',
  templateUrl: './course-list.component.html'
})
export class CourseListComponent {
  isLoading = false;
  lessons: Lesson[] = [
    { id: 1, title: 'Angular CLI', completed: true },
    { id: 2, title: 'Component', completed: false },
    { id: 3, title: 'Directives', completed: false }
  ];

  // trackBy ช่วยให้ Angular รู้ว่ารายการใดเป็นรายการเดิม
  trackByLessonId(index: number, lesson: Lesson): number {
    return lesson.id;
  }
}

// ตัวอย่างการใช้งาน:
// <app-course-list></app-course-list>
<!-- course-list.component.html -->
<ng-container *ngIf="!isLoading; else loading">
  <ul>
    <li
      *ngFor="let lesson of lessons; let i = index; trackBy: trackByLessonId"
      [ngClass]="{ 'done': lesson.completed, 'pending': !lesson.completed }"
      [ngStyle]="{ 'font-weight': lesson.completed ? '700' : '400' }">
      {{ i + 1 }}. {{ lesson.title }}
    </li>
  </ul>
</ng-container>

<ng-template #loading>
  <p>กำลังโหลดข้อมูล...</p>
</ng-template>

กิจกรรมท้ายบท

  1. สร้างรายการบทเรียนอย่างน้อย 5 รายการ
  2. ใช้ *ngFor แสดงรายการ
  3. ใช้ *ngIf แสดงข้อความเมื่อไม่มีรายการ
  4. ใช้ ngClass เปลี่ยนสีรายการที่เรียนจบแล้ว

กลับสัปดาห์ที่ 7