angular component คือ — คู่มือฉบับสมบูรณ์ 2026
angular component คืออะไร — องค์ประกอบพื้นฐานของ Angular
Angular Component คือหน่วยสร้าง (building block) พื้นฐานของแอปพลิเคชัน Angular ที่ประกอบด้วย Template, Logic และ Style ที่ทำงานร่วมกันเป็นอิสระ แต่ละ
Component มีหน้าที่เฉพาะและสามารถประกอบเข้าด้วยกันเพื่อสร้าง UI ที่ซับซ้อนได้
ในมุมมองของนักพัฒนาที่มีประสบการณ์กว่า 13 ปีกับ Angular ผมมองว่า Component คือ "เลโก้" ของโลกการพัฒนาเว็บ — คุณสามารถสร้างสิ่งต่าง ๆ จากบล็อกเล็ก ๆ ที่ออกแบบมาอย่างดี โดยแต่ละบล็อกมีหน้าที่ชัดเจน
Component ประกอบด้วย 3 ส่วนหลัก:
- Template — HTML ที่กำหนดโครงสร้าง UI
- Class — TypeScript ที่จัดการ logic และ state
- Styles — CSS ที่ควบคุมการแสดงผล
เมื่อคุณสร้าง Angular App ใหม่ Angular CLI จะสร้าง Root Component ให้โดยอัตโนมัติ ซึ่งมักจะเป็น `app.component` — นี่คือจุดเริ่มต้นของแอปพลิเคชันทั้งหมด
Angular Component คือหน่วยการสร้าง (building block) พื้นฐานของแอปพลิเคชัน Angular ที่นำ HTML, CSS, และ TypeScript มาทำงานร่วมกันเป็นโมดูลที่ทำงานได้สมบูรณ์ Component แต่ละตัวประกอบด้วย template สำหรับแสดงผล, style สำหรับกำหนดรูปแบบ, และ class สำหรับจัดการ logic การทำงาน
Component ทำงานบนหลักการ "Encapsulation" ที่ทำให้แต่ละส่วนสามารถพัฒนา ทดสอบ และใช้งานได้อย่างอิสระ โดยไม่กระทบกับส่วนอื่น ๆ ในแอปพลิเคชัน การออกแบบแบบนี้ช่วยให้ทีมพัฒนาขนาดใหญ่สามารถทำงานร่วมกันได้อย่างมีประสิทธิภาพ เพราะแต่ละคนสามารถรับผิดชอบ component ของตัวเองได้
ในทางปฏิบัติ Component คือ "บล็อกตัวต่อ" ที่นักพัฒนาใช้สร้าง UI ที่ซับซ้อนจากชิ้นส่วนเล็ก ๆ ที่จัดการง่าย ตัวอย่างเช่น ปุ่ม, ฟอร์ม, ตารางข้อมูล, หรือแม้แต่หน้าเว็บทั้งหน้าสามารถถูกออกแบบเป็น component แยกกันได้
Angular Component คือ building block พื้นฐานของทุก Angular application เราสามารถมอง component เป็น "ส่วนประกอบ" ที่รวม template, logic และ style เข้าด้วยกันเป็นหน่วยเดียว แต่ละ component มีหน้าที่เฉพาะและสามารถนำกลับมาใช้ใหม่ได้ทั่วทั้งแอป
ตัวอย่างเช่น ในแอป e-commerce เราอาจมี `ProductCardComponent` สำหรับแสดงสินค้า, `ShoppingCartComponent` สำหรับตะกร้าสินค้า และ `HeaderComponent` สำหรับส่วนหัวของหน้า ทุก component เหล่านี้ทำงานร่วมกันเพื่อสร้างประสบการณ์ผู้ใช้ที่สมบูรณ์
สิ่งที่ทำให้ component ต่างจาก directive หรือ service คือ component มี template ของตัวเองเสมอ ทำให้มันเหมาะสำหรับสร้าง UI elements ที่ซับซ้อนและสามารถนำกลับมาใช้ใหม่ได้
Angular Component คือหน่วยการสร้างหลักของแอปพลิเคชัน Angular ทั้งหมด ทุกสิ่งที่คุณเห็นบนหน้าจอ — ปุ่ม, ฟอร์ม, ตาราง, โมดอล, แม้แต่แอปทั้งแอป — ล้วนถูกสร้างจาก components ที่ทำงานร่วมกัน
Component ไม่ใช่แค่ template HTML แต่เป็นชุดของ 3 ส่วนที่ทำงานร่วมกัน: Template (HTML ที่กำหนด UI), Class (TypeScript ที่กำหนด logic และ data), และ Metadata (ข้อมูลอธิบายว่า component นี้ชื่ออะไร ใช้ template อะไร selector อะไร) ซึ่งทำให้ Angular สามารถ render และจัดการ lifecycle ของ component ได้อย่างถูกต้อง
ในแง่ของ trading platform ที่เราใช้กัน daily — คุณสามารถมอง component เหมือนกับ widget บน dashboard XM ของคุณ เช่น chart widget, order book widget, position widget แต่ละ widget มี template ของตัวเอง มี logic ของตัวเอง แต่ทำงานร่วมกันเป็น dashboard ที่สมบูรณ์
โครงสร้างและ Anatomy ของ Component
ทุก Component ใน Angular มีโครงสร้างมาตรฐานที่เข้าใจง่าย:
import { Component } from '@angular/core';
@Component({ selector: 'app-my-component', templateUrl: './my-component.html', styleUrls: ['./my-component.css'] }) export class MyComponent { title = 'My Component'; items = [];
ngOnInit() { this.loadItems(); }
loadItems() { // Fetch data logic } }
@Component Decorator คือหัวใจสำคัญ — มันบอก Angular ว่า Class นี้เป็น Component และกำหนด metadata สำคัญ:
| Property | Description | Example |
|---|---|---|
| selector | CSS selector สำหรับใช้ Component | `app-my-component` |
| templateUrl | Path ถึง HTML template | `'./my-component.html'` |
| template | Inline HTML template | `'Hello'` |
| styleUrls | Path ถึง CSS files | `['./my-component.css']` |
| styles | Inline CSS | `['h1 { color: red; }']` |
Lifecycle Hooks เป็นฟีเจอร์สำคัญที่ Component มี:
- `ngOnInit()` — เรียกเมื่อ Component ถูก initialize
- `ngOnChanges()` — เรียกเมื่อ input properties เปลี่ยน
- `ngOnDestroy()` — เรียกก่อน Component ถูกทำลาย
Component ของ Angular ประกอบด้วย 3 ส่วนหลักที่ต้องทำงานร่วมกัน:
1. Template (HTML) — ส่วนที่กำหนดโครงสร้างและรูปแบบการแสดงผล ใช้ HTML ปกติร่วมกับ Angular directives เช่น ngIf, ngFor, [(ngModel)] เพื่อสร้าง UI ที่ตอบสนองต่อการเปลี่ยนแปลงของข้อมูล
2. Style (CSS) — ส่วนที่กำหนดรูปแบบการแสดงผล สามารถใช้ CSS, SCSS, หรือ LESS ได้ โดย default จะถูก encapsulate ไว้ใน component นั้น ๆ ไม่กระทบ component อื่น
3. Class (TypeScript) — ส่วนที่จัดการ logic การทำงาน, state, และ interaction กับบริการต่าง ๆ ใช้ decorator @Component เพื่อระบุ metadata
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
title: string = 'Hello World';
}
Component หนึ่งชิ้นประกอบด้วย 3 ส่วนหลัก คือ Template (HTML), Logic (TypeScript) และ Style (CSS) ซึ่งทั้งหมดถูกผูกเข้าด้วยกันผ่าน decorator `@Component` ที่ระบุ metadata ต่างๆ
Template คือส่วน HTML ที่กำหนด layout และโครงสร้างของ UI เราสามารถใช้ Angular directives เช่น `ngIf`, `ngFor`, และ `(click)` เพื่อเพิ่ม interactivity ได้โดยตรงใน template
Logic ส่วน TypeScript จะจัดการ state, business logic และ interaction กับ services เราใช้ properties และ methods เพื่อควบคุมข้อมูลที่แสดงใน template ผ่าน data binding
Style ส่วน CSS จะกำหนด appearance ของ component โดยเฉพาะ เราสามารถใช้ `encapsulation: ViewEncapsulation.Emulated` เพื่อให้ style มีผลเฉพาะกับ component นั้นๆ ไม่กระทบ component อื่น
เมื่อสร้าง Angular component ด้วย CLI คุณจะได้ไฟล์ 4 ไฟล์หลัก:
component.ts — Class หลักที่มี metadata decorator `@Component` ซึ่งระบุ selector, template, styles, และ lifecycle hooks นี่คือ "สมอง" ของ component ที่จัดการ state, logic, และ communication
component.html — Template ที่กำหนด UI ใช้ Angular directives เช่น ngIf, ngFor, [()] binding เพื่อสร้าง dynamic content ที่ตอบสนองต่อ data changes
component.scss — Styles เฉพาะของ component ใช้ encapsulation ทำให้ styles ไม่กระทบ component อื่น (คล้ายกับ scoped CSS ใน React)
component.spec.ts — Unit test file สำหรับ testing component behavior
ใน metadata decorator คุณจะพบ properties สำคัญเช่น `selector` (CSS selector ที่ใช้เรียก component), `templateUrl` (path ไปยัง HTML file), `styleUrls` (array ของ style files), และ `providers` (dependency injection tokens)
การสื่อสารระหว่าง Components
หนึ่งในความท้าทายที่ใหญ่ที่สุดในการพัฒนา Angular คือการทำให้ Components สื่อสารกันได้อย่างมีประสิทธิภาพ Angular มีกลไกหลายอย่างสำหรับเรื่องนี้:
Parent to Child — @Input() // Child component @Input() message: string;
// Parent template
Child to Parent — @Output() และ EventEmitter
// Child component
@Output() itemSelected = new EventEmitter
selectItem(item: string) { this.itemSelected.emit(item); }
// Parent template
Service-based Communication
@Injectable({ providedIn: 'root' })
export class SharedService {
private subject = new BehaviorSubject
updateMessage(msg: string) { this.subject.next(msg); } }
@ViewChild สำหรับ Parent Access Child Directly @ViewChild('childComp') childComponent: ChildComponent;
ngAfterViewInit() { this.childComponent.doSomething(); }
การสื่อสารระหว่าง component เป็นหัวใจสำคัญของการพัฒนาแอปพลิเคชัน Angular มี 4 วิธีหลัก:
1. @Input() — ส่งข้อมูลจาก parent ไปยัง child component ใช้สำหรับส่งค่าที่อ่านอย่างเดียว (read-only)
// Child component
@Input() userName: string;
// Parent template
2. @Output() และ EventEmitter — ส่งข้อมูลจาก child ไปยัง parent ใช้สำหรับแจ้งเหตุการณ์ต่าง ๆ
// Child component
@Output() itemSelected = new EventEmitter
// Parent template
3. Services — ใช้สำหรับสื่อสารระหว่าง component ที่ไม่มีความสัมพันธ์ parent-child โดยตรง ผ่าน dependency injection
4. ViewChild/ViewChildren — Parent เข้าถึงและควบคุม child component โดยตรง
การสื่อสารระหว่าง components เป็นหัวใจสำคัญของ Angular application เราสามารถสื่อสารได้หลายวิธีตามความสัมพันธ์ของ components
Parent-to-Child ใช้ `@Input()` decorator เพื่อส่งข้อมูลจาก parent ไปยัง child component ตัวอย่างเช่น parent ส่ง product data ไปยัง `ProductCardComponent` เพื่อแสดงข้อมูลสินค้า
Child-to-Parent ใช้ `@Output()` decorator พร้อม `EventEmitter` เพื่อส่งข้อมูลหรือเหตุการณ์จาก child กลับไปยัง parent เช่น เมื่อ user กดปุ่ม "Add to Cart" ใน child component
Shared Service ใช้ service ที่ inject เข้าในหลาย components เพื่อแชร์ข้อมูลหรือ state ร่วมกัน วิธีนี้เหมาะสำหรับข้อมูลที่ต้องใช้ทั่วทั้งแอป เช่น user authentication state หรือ shopping cart data
การสื่อสารระหว่าง components เป็นหัวใจสำคัญของการสร้างแอปพลิเคชันที่ซับซ้อน Angular มี 4 mechanisms หลัก:
@Input() — Parent ส่งข้อมูลไปยัง child component ผ่าน property binding เช่น `
@Output() — Child ส่ง event กลับไปยัง parent ผ่าน EventEmitter เช่น `
Services — Components ที่ไม่ได้อยู่ใน parent-child relationship สื่อสารผ่าน shared services ที่ inject ผ่าน dependency injection
@ViewChild / @ContentChild — Parent เข้าถึง child component instance โดยตรงเพื่อเรียก methods หรือ properties
ใน trading app ตัวอย่างเช่น parent dashboard component ส่ง market data ผ่าน @Input() ไปยัง chart component, chart component ส่ง click events กลับผ่าน @Output() เพื่อ trigger order placement, และทั้ง dashboard และ order book ใช้ shared MarketService เพื่อรับ real-time price updates
Best Practices สำหรับ Component Design
จากประสบการณ์ 13 ปีในการพัฒนา Angular ผมได้เรียนรู้ best practices หลายประการ:
1. Single Responsibility Principle แต่ละ Component ควรทำหน้าที่เดียวเท่านั้น — ถ้า Component มีหน้าที่หลายอย่าง ให้แยกออกเป็นส่วนย่อย ๆ
2. Small and Focused Templates Template ควรสั้นและอ่านง่าย — ถ้ายาวเกิน 50 บรรทัด พิจารณาแยกเป็น Component ย่อย
3. Use OnPush Change Detection @Component({ selector: 'app-optimized', changeDetection: ChangeDetectionStrategy.OnPush, template: '...' }) OnPush จะทำให้ Angular ตรวจสอบ Component เฉพาะเมื่อ input properties เปลี่ยน — ปรับปรุง performance อย่างมีนัยสำคัญ
4. Immutable Data ใช้ immutable data structures เพื่อให้ง่ายต่อการ track changes: // Instead of mutating this.items.push(newItem);
// Create new array this.items = [...this.items, newItem];
5. Lazy Loading for Large Apps const routes: Routes = [ { path: 'admin', loadChildren: () => import('./admin/admin.module') .then(m => m.AdminModule) } ];
Single Responsibility Principle — แต่ละ component ควรรับผิดชอบงานเพียงอย่างเดียว ทำให้เข้าใจง่ายและบำรุงรักษาง่าย
Component Size — ควรจำกัดขนาด template ไม่เกิน 50 บรรทัด และ class ไม่เกิน 100 บรรทัด หากเกินควรแบ่งเป็น sub-components
Naming Convention — ใช้ prefix 'app-' สำหรับ selector เช่น app-header, app-footer เพื่อให้ชัดเจนว่าเป็นส่วนหนึ่งของแอปพลิเคชัน
Input/Output Design — ออกแบบให้ @Input() เป็น read-only และใช้ @Output() สำหรับส่งเหตุการณ์กลับ ไม่ควรให้ child แก้ไข input โดยตรง
Lazy Loading — ใช้สำหรับ component ที่ไม่ใช่ critical เพื่อลดขนาด initial bundle และเพิ่มความเร็วในการโหลด
Change Detection Strategy — ใช้ OnPush สำหรับ component ที่ไม่เปลี่ยนแปลงบ่อย เพื่อเพิ่มประสิทธิภาพ
การออกแบบ component ที่ดีมีผลต่อ maintainability และ scalability ของ application อย่างมาก เราควรยึดหลัก Single Responsibility โดยให้แต่ละ component ทำหน้าที่เดียวให้ดีที่สุด
ตั้งชื่อ component ให้สื่อความหมายชัดเจน เช่น `UserProfileComponent`, `OrderHistoryComponent` แทนที่จะใช้ชื่อคลุมเครืออย่าง `Comp1` หรือ `Widget`
แยก template ออกเป็นไฟล์ `.html` แยกต่างหากจาก `.ts` file เมื่อ template มีขนาดใหญ่เกิน 20-30 บรรทัด จะช่วยให้ code อ่านง่ายและ maintain ได้ดี
ใช้ `@Input()` และ `@Output()` ให้เหมาะสม โดย `@Input()` สำหรับข้อมูลไหลลง (parent→child) และ `@Output()` สำหรับเหตุการณ์ไหลขึ้น (child→parent)
ทดสอบ component แต่ละตัวแยกกันด้วย unit tests เพื่อให้มั่นใจว่า component ทำงานถูกต้องตาม expectation ก่อนนำไปประกอบเป็น application จริง
จากประสบการณ์ 13 ปีในการพัฒนา trading systems ผมมี best practices สำหรับ Angular component design:
Single Responsibility — แต่ละ component ควรทำสิ่งเดียวให้ดีที่สุด Chart component ควร rendering chart ไม่ควรจัดการ order logic
Small and Focused — Components ควรมีขนาดเล็กระมัดระวัง (template < 100 lines, class < 150 lines) ถ้าใหญ่เกินให้ split เป็น sub-components
Use ViewEncapsulation — ใช้ `ViewEncapsulation.Emulated` (default) เพื่อให้ styles ถูก encapsulate แต่ใช้ `None` เมื่อต้องการ global styles
Lazy Load Components — ใช้ dynamic component loading สำหรับ components ที่ไม่จำเป็นต้องโหลดทันที เช่น modal dialogs
Test Thoroughly — เขียน unit tests สำหรับ component behavior, template rendering, และ input/output handling
Document with JSDoc — ใช้ JSDoc comments สำหรับ public APIs ของ component เพื่อให้ developer อื่นเข้าใจง่าย
ตัวอย่างจริง: สร้าง Todo Component
มาสร้าง Todo Component ที่สมบูรณ์ซึ่งแสดง best practices หลายประการ:
todo-item.component.ts import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({ selector: 'app-todo-item', template: `
{{ item.text }}
toggleComplete() { this.toggle.emit(this.item); } }
todo-list.component.ts import { Component } from '@angular/core';
@Component({ selector: 'app-todo-list', template: `
Todo List
addTodo() { if (this.newItem.trim()) { this.todos.push({ id: Date.now(), text: this.newItem, completed: false }); this.newItem = ''; } }
toggleItem(item) { item.completed = !item.completed; }
deleteItem(id: number) { this.todos = this.todos.filter(t => t.id !== id); } }
ตัวอย่างนี้แสดงการใช้ @Input, @Output, ngFor, ngModel และ event handling — แนวคิดพื้นฐานทั้งหมดที่คุณต้องเข้าใจเมื่อทำงานกับ Angular Components
สร้าง Todo Component ที่สมบูรณ์เพื่อแสดงการใช้งานจริง:
@Component({
selector: 'app-todo',
template: `
รายการงาน
-
{{ task.name }}
`,
styleUrls: ['./todo.component.css']
})
export class TodoComponent {
tasks: Task[] = [];
newTask: string = '';
addTask(): void {
if (this.newTask.trim()) {
this.tasks.push({ name: this.newTask, completed: false });
this.newTask = '';
}
}
deleteTask(task: Task): void {
this.tasks = this.tasks.filter(t => t !== task);
}
}
ตัวอย่างนี้แสดง component ที่มี state การจัดการ, template ที่ใช้ directives, และ interaction กับผู้ใช้ เป็นพื้นฐานที่นำไปขยายเป็นแอปพลิเคชันที่ซับซ้อนขึ้นได้
ให้เราสร้าง `TodoItemComponent` ที่แสดงรายการงานพร้อมความสามารถในการ mark complete และ delete
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-todo-item',
template: `
{{ title }}
`,
styles: [`
.todo-item { display: flex; align-items: center; gap: 8px; padding: 8px; }
.completed span { text-decoration: line-through; color: #888; }
`]
})
export class TodoItemComponent {
@Input() title: string = '';
@Input() completed: boolean = false;
@Output() toggle = new EventEmitter
@Output() delete = new EventEmitter
toggleComplete() { this.toggle.emit(); }
}
Parent component ใช้ `*ngFor` เพื่อ render รายการ todo ทั้งหมด:
*ngFor="let todo of todos" [title]="todo.title" [completed]="todo.completed" (toggle)="toggleTodo(todo)" (delete)="deleteTodo(todo)">
คำถามที่พบบ่อย
Component กับ Directive ต่างกันอย่างไร?
Component คือ Directive ประเภทพิเศษที่มี Template — ทุก Component เป็น Directive แต่ไม่ใช่ทุก Directive เป็น Component Directive ใช้สำหรับการเปลี่ยนแปลง DOM โดยตรง (เช่น ngIf, ngFor) หรือการเพิ่มพฤติกรรม (เช่น custom directives) โดยไม่มี template ของตัวเอง
Component มี @Component decorator และต้องมี template ในขณะที่ Directive ใช้ @Directive decorator และมักจะไม่มีการแสดงผลของตัวเอง แต่เปลี่ยนพฤติกรรมหรือลักษณะของ element ที่มีอยู่
เมื่อไหร่ควรใช้ Service แทน Component?
ใช้ Service เมื่อคุณต้องการแชร์ logic หรือ data ระหว่าง Components หลาย ๆ ตัว Service เหมาะสำหรับการจัดการ HTTP requests, state management และ business logic ที่ไม่เกี่ยวกับ UI โดยตรง
Component ควรโฟกัสที่การแสดงผลและการโต้ตอบกับผู้ใช้ ในขณะที่ Service จัดการ logic ที่ซับซ้อน การแยก concern แบบนี้ทำให้โค้ดง่ายต่อการทดสอบและบำรุงรักษา
Angular Component รองรับ Server-Side Rendering ได้หรือไม่?
ใช่ Angular รองรับ Server-Side Rendering (SSR) ผ่าน Angular Universal SSR ช่วยปรับปรุง performance และ SEO โดยสร้าง HTML ที่สมบูรณ์บน server ก่อนส่งไปยัง client
คุณต้องติดตั้ง @angular/platform-server และตั้งค่า build process ให้สร้างทั้ง client-side และ server-side bundles สำหรับ production deployment ที่ซับซ้อนอาจต้องการ Node.js server เพื่อรัน server-side rendering
แนะนำเพิ่มเติม
🎯 เปิดบัญชี XM Forex → สมัคร
📱 แอป iCafeFX → ดาวน์โหลด
📊 สัญญาณฟรี → รับสัญญาณ
📚 คู่มือเทรด → SiamCafeBook
🤝 สมัคร Partner XM → pipaffiliates.com/c?c=72816&l=th&p=6
แนะนำจากเครือข่าย SiamCafe
คู่มือ Forex ที่เกี่ยวข้อง
แหล่งอ้างอิง
- SiamCafe.net - ชุมชนไอทีไทยตั้งแต่ปี 1997
- iCafeFX.com - ศูนย์วิเคราะห์ Forex และทองคำ