ภาพรวม
เมื่อต้องการกำหนด CSS Style ให้ Row หรือ Cell ในตารางแบบ Dynamic (ขึ้นกับข้อมูล/เงื่อนไข) สามารถทำได้หลายวิธี ขึ้นอยู่กับ Framework ที่ใช้ (SAPUI5, HTML ธรรมดา, React, Vue, etc.)
วิธีที่ 1: CSS Class แบบ Static + Conditional Class (General)
/* CSS */
.sapMListTbl .highlight-row {
background-color: #fff3cd;
color: #856404;
}
.sapMListTbl .error-row {
background-color: #f8d7da;
color: #721c24;
}
.sapMListTbl .success-cell {
font-weight: bold;
color: #155724;
}
JavaScript/TypeScript (Dynamic Class Assignment)
// สมมติใช้ SAPUI5 / OpenUI5
const row = new sap.m.ColumnListItem({
cells: [
new sap.m.Text({ text: "{Name}" }),
new sap.m.Text({
text: "{Status}",
// ใช้ Formatter กำหนด Class
className: {
path: "Status",
formatter: function(status) {
switch(status) {
case "Error": return "error-row";
case "Warning": return "highlight-row";
case "Success": return "success-cell";
default: return "";
}
}
}
})
]
});
วิธีที่ 2: Row Settings ใน SAPUI5 Table
const table = new sap.m.Table({
items: {
path: "/Data",
template: new sap.m.ColumnListItem({
type: "Navigation",
cells: [ /* ... cells ... */ ]
})
}
});
// ใช้ RowSettings สำหรับ Highlight ทั้ง Row
table.setRowSettingsTemplate(new sap.m.RowSettings({
highlight: "{Status}", // "None", "Information", "Success", "Warning", "Error"
// หรือใช้ Expression Binding
highlight: "{= ${Status} === 'Error' ? 'Error' : 'None' }"
}));
วิธีที่ 3: HTML/JavaScript ธรรมดา (Vanilla)
// HTML
<table id="dataTable">
<tbody></tbody>
</table>
<style>
.row-high { background: #fff3cd; }
.row-low { background: #d4edda; }
.cell-negative { color: #dc3545; font-weight: bold; }
</style>
<script>
const data = [
{ name: "Product A", value: 150, status: "high" },
{ name: "Product B", value: -20, status: "low" },
{ name: "Product C", value: 300, status: "high" }
];
const tbody = document.querySelector("#dataTable tbody");
data.forEach(item => {
const tr = document.createElement("tr");
// Dynamic Class ตามเงื่อนไข
tr.className = item.status === "high" ? "row-high" : "row-low";
tr.innerHTML = `
<td>${item.name}</td>
<td class="${item.value < 0 ? 'cell-negative' : ''}">${item.value}</td>
<td>${item.status}</td>
`;
tbody.appendChild(tr);
});
</script>
วิธีที่ 4: React / Vue / Angular (Framework Pattern)
// React Example
const Row = ({ item }) => (
<tr className={item.status === 'high' ? 'row-high' : 'row-low'}>
<td>{item.name}</td>
<td className={item.value < 0 ? 'cell-negative' : ''}>{item.value}</td>
<td>{item.status}</td>
</tr>
);
// Vue Example
<tr :class="{ 'row-high': item.status === 'high', 'row-low': item.status === 'low' }">
<td>{{ item.name }}</td>
<td :class="{ 'cell-negative': item.value < 0 }">{{ item.value }}</td>
</tr>
Best Practices
- แยก Logic การตัดสินใจ Class ไปเป็น Function/Formatter แยกต่างหาก
- ใช้ CSS Variables สำหรับค่าสีที่เปลี่ยนแปลงได้
- หลีกเลี่ยง Inline Style (style="...") ใช้ Class แทน
- ใน SAPUI5: ใช้
RowSettingsหรือformatterใน Binding - Performance: สำหรับข้อมูลเยอะ ใช้ Virtual Scrolling / Pagination