Data Binding คือการเชื่อมข้อมูลระหว่าง Class ของ Component กับ Template ทำให้ UI แสดงข้อมูลและตอบสนองต่อการกระทำของผู้ใช้ได้อย่างเป็นระบบ
%%{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["ยุค DOM Manual / Manual Update"]
A["querySelector + innerHTML
อัปเดตเอง"]
end
subgraph Era2["ยุค Template Binding / Binding Era"]
B["Interpolation
แสดงค่า"]
C["Property/Event Binding
รับส่งค่า"]
end
subgraph Era3["ยุค Reactive UI / Reactive Era"]
D["Two-way Binding
ฟอร์มโต้ตอบ"]
E["Change Detection
อัปเดต UI อัตโนมัติ"]
end
A --> B --> C --> D --> E
{{ expression }} เพื่อแสดงค่าตัวแปรใน Template[src]="imageUrl" เพื่อผูก Property ของ HTML กับตัวแปร(click)="handleClick($event)" เพื่อผูก Event กับ Method[(ngModel)]="username" และต้อง import FormsModule[class.active]="isActive" หรือ [ngClass][style.color]="color" หรือ [ngStyle]| ประเภท | Syntax | ทิศทางข้อมูล | ตัวอย่าง |
|---|---|---|---|
| Interpolation | {{ title }} |
Class ไป Template | แสดงข้อความ |
| Property | [src]="imageUrl" |
Class ไป DOM Property | รูปภาพ |
| Event | (click)="save()" |
Template ไป Class | ปุ่มคลิก |
| Two-way | [(ngModel)]="name" |
สองทิศทาง | ฟอร์ม |
| Class | [class.active]="ok" |
Class ไป CSS Class | สถานะ active |
| Style | [style.color]="color" |
Class ไป Inline 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 LR
A["Component Class
ข้อมูลและ Methods"] -->|Interpolation/Property| B["Template
หน้าจอ"]
B -->|Event Binding| A
A <-->|Two-way Binding| C["Form Control
ช่องกรอกข้อมูล"]
// profile.component.ts
// Component นี้แสดงตัวอย่าง Binding หลายรูปแบบ
import { Component } from '@angular/core';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html'
})
export class ProfileComponent {
username = 'student';
imageUrl = 'assets/profile.png';
isActive = true;
textColor = '#2563eb';
// Event handler เมื่อผู้ใช้กดปุ่ม
toggleActive(): void {
this.isActive = !this.isActive;
}
}
// ตัวอย่างการใช้งาน:
// ต้อง import FormsModule หากใช้ [(ngModel)]
// <app-profile></app-profile>
<!-- profile.component.html -->
<h2>สวัสดี {{ username }}</h2>
<img [src]="imageUrl" alt="Profile image" width="120">
<input [(ngModel)]="username" placeholder="กรอกชื่อผู้ใช้">
<p [class.active]="isActive" [style.color]="textColor">
สถานะ: {{ isActive ? 'Active' : 'Inactive' }}
</p>
<button type="button" (click)="toggleActive()">Toggle Status</button>
[(ngModel)]isActive