Component คือหน่วยหลักของ UI ใน Angular ประกอบด้วย Class, Template, Style และ Metadata จาก @Component decorator เพื่อบอก Angular ว่า Component นี้ใช้ selector ใดและมีหน้าตาอย่างไร
%%{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["ยุคหน้าเดียว / Page Script"]
A["HTML + JS ปนกัน
Hard to Reuse"]
end
subgraph Era2["ยุค Component / Component Model"]
B["แยก UI เป็นชิ้น
Reusable Component"]
C["@Component Metadata
ประกาศ selector/template/style"]
end
subgraph Era3["ยุคออกแบบระบบ / Design System"]
D["Nested Components
ประกอบเป็นหน้าจอ"]
E["Shared Components
ใช้ซ้ำทั้งระบบ"]
end
A --> B --> C --> D --> E
@Componentselector เช่น 'app-header' ใช้ใน Template เป็น <app-header>templateUrl ชี้ไปยังไฟล์ HTML ภายนอกstyleUrls ชี้ไปยังไฟล์ CSS ภายนอกtemplate: '<h1>Hello</h1>'styles: ['h1 { color: red; }']Emulated, ShadowDom, None| วิธีเขียน | ตัวอย่าง | เหมาะกับ |
|---|---|---|
templateUrl |
templateUrl: './header.html' |
Component ที่มี HTML หลายบรรทัด |
template |
template: '<h1>Hello</h1>' |
Component ขนาดเล็ก |
styleUrls |
styleUrls: ['./header.css'] |
CSS ที่ต้องดูแลแยก |
styles |
styles: ['h1 { color:red }'] |
Style สั้น ๆ เฉพาะจุด |
%%{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["@Component
Metadata"] --> B["selector
ชื่อเรียกใน HTML"]
A --> C["template/templateUrl
โครงสร้าง UI"]
A --> D["styles/styleUrls
รูปแบบ CSS"]
A --> E["class
ข้อมูลและ method"]
E --> F["Template Binding
เชื่อมข้อมูลกับ UI"]
// lesson-card.component.ts
// Component สำหรับแสดงข้อมูลบทเรียน 1 รายการ
import { Component } from '@angular/core';
@Component({
selector: 'app-lesson-card',
templateUrl: './lesson-card.component.html',
styleUrls: ['./lesson-card.component.css']
})
export class LessonCardComponent {
title = 'Angular Component';
description = 'เรียนรู้การสร้าง Component และการใช้ selector';
// method สำหรับเปลี่ยนชื่อบทเรียน
updateTitle(): void {
this.title = 'Updated Angular Component';
}
}
// ตัวอย่างการใช้งาน:
// <app-lesson-card></app-lesson-card>
<!-- lesson-card.component.html -->
<article class="lesson-card">
<h2>{{ title }}</h2>
<p>{{ description }}</p>
<button type="button" (click)="updateTitle()">Update</button>
</article>
/* lesson-card.component.css */
.lesson-card {
border: 1px solid #ddd;
padding: 16px;
}
course-headerapp-course-headerapp.component.html