Angular Material: ใช้ UI Component Library อย่างมืออาชีพ
#angular12 เม.ย. 2569
Angular Material คืออะไร
Angular Material เป็น UI component library อย่างเป็นทางการของ Angular ออกแบบตาม Material Design ของ Google
ติดตั้ง
ng add @angular/material
Button
<button mat-button>Basic</button>
<button mat-raised-button color="primary">Raised</button>
<button mat-fab color="accent">
<mat-icon>add</mat-icon>
</button>
Form Fields
<mat-form-field appearance="outline">
<mat-label>Email</mat-label>
<input matInput type="email" [formControl]="emailControl" />
<mat-error *ngIf="emailControl.hasError('email')">
Email ไม่ถูกต้อง
</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>เลือกประเทศ</mat-label>
<mat-select [formControl]="countryControl">
<mat-option value="th">ไทย</mat-option>
<mat-option value="jp">ญี่ปุ่น</mat-option>
</mat-select>
</mat-form-field>
Table
@Component({
imports: [MatTableModule],
template: `
<table mat-table [dataSource]="users">
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef>ชื่อ</th>
<td mat-cell *matCellDef="let user">{{ user.name }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columns"></tr>
<tr mat-row *matRowDef="let row; columns: columns"></tr>
</table>
`
})
export class UserTableComponent {
columns = ['name', 'email'];
users = [{ name: 'สมชาย', email: 'somchai@example.com' }];
}
Dialog
import { MatDialog } from '@angular/material/dialog';
export class MyComponent {
constructor(private dialog: MatDialog) {}
openDialog() {
const ref = this.dialog.open(ConfirmDialogComponent, {
width: '400px',
data: { message: 'ต้องการลบข้อมูลนี้ไหม?' }
});
ref.afterClosed().subscribe(result => {
if (result) this.deleteItem();
});
}
}
Snackbar
import { MatSnackBar } from '@angular/material/snack-bar';
this.snackBar.open('บันทึกสำเร็จ', 'ปิด', { duration: 3000 });
สรุป
Angular Material ช่วยประหยัดเวลาสร้าง UI ได้มาก มี component ครบครัน accessible และ responsive ออกแบบมาให้ทำงานร่วมกับ Angular ได้ดีที่สุดครับ