如何在Angular 8中展示API返回的attributes数组至HTML表格
解决方案:将API返回的Attributes数据展示为HTML表格
没问题,这就帮你实现把API返回的attributes数据展示到HTML表格里的需求!
1. 静态HTML表格(数据固定时适用)
如果你的数据是固定不变的,直接写静态HTML表格就能达到你要的效果:
<table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th><strong>CustName</strong></th> <th><strong>VIN</strong></th> </tr> </thead> <tbody> <tr> <td>XYZ</td> <td>10XYAZHSKS</td> </tr> <tr> <td>ABC Dealer</td> <td>98GSBS8S6D</td> </tr> </tbody> </table>
我加了border、cellpadding和cellspacing属性让表格看起来更清晰,你可以根据需求调整样式,比如用CSS替代行内属性来美化。
2. 动态生成表格(从API实时获取数据时适用)
如果数据是从API动态获取的,用JavaScript处理返回数据并生成表格会更灵活:
步骤1:准备基础HTML结构
先在页面上创建一个空表格,留好表头:
<table id="customerTable" border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th><strong>CustName</strong></th> <th><strong>VIN</strong></th> </tr> </thead> <tbody> <!-- 动态生成的行将插入到这里 --> </tbody> </table>
步骤2:用JavaScript处理API数据
假设你已经通过接口请求拿到了返回数据,用以下代码提取attributes并生成表格行:
// 模拟API返回的数据(实际项目中替换为真实的接口响应) const apiResponse = { "data": [ { "id": "sdff12", "documentTypeId": "617ffgv22", "fileType": "TIFF", "attributes": [ { "attributeId": "1", "customerName": "XYZ", "VIN": "10XYAZHSKS" }, { "attributeId": "2", "customerName": "ABC Dealer", "VIN": "98GSBS8S6D" } ] } ] }; // 提取需要展示的attributes数组 const customerData = apiResponse.data[0].attributes; // 获取表格的tbody元素 const tableBody = document.getElementById('customerTable').querySelector('tbody'); // 循环遍历数据,生成每一行 customerData.forEach(item => { // 创建表格行 const row = document.createElement('tr'); // 创建客户名称单元格并赋值 const nameCell = document.createElement('td'); nameCell.textContent = item.customerName; // 创建VIN单元格并赋值 const vinCell = document.createElement('td'); vinCell.textContent = item.VIN; // 将单元格添加到行,再将行添加到tbody row.appendChild(nameCell); row.appendChild(vinCell); tableBody.appendChild(row); });
这样无论API返回的attributes数据怎么变化,表格都会自动更新对应的内容。
内容的提问来源于stack exchange,提问作者Angel Reji
相关产品推荐
相关产品推荐

