Angular 4中在表格内展示JSON数据的实现方法
在Angular 4中展示JSON数据到表格的实现方案
没问题,我来帮你搞定在Angular 4里把这份JSON数据展示成表格的事儿!咱们一步步来:
1. 组件内处理数据转换
首先啊,你这份JSON数据是对象格式的(键是0、1、2这种),但Angular的*ngFor指令只能遍历数组,所以咱们得先把它转换成数组。在你的组件类里这么做:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-stock-table', templateUrl: './stock-table.component.html', styleUrls: ['./stock-table.component.css'] }) export class StockTableComponent implements OnInit { // 原始JSON数据 rawStockData = { "0": { "open": 93.3, "high": 96, "low": 93.3, "close": 95.04, "volume": 358172, "score": "100", "symbol": "ZBRA", "company_name": "Zebra Technologies Corp.", "company_sector": "Industrial Goods" }, "1": { "open": 19.1396, "high": 19.5578, "low": 18.7612, "close": 19.3587, "volume": 185112, "score": "100", "symbol": "ZEUS", "company_name": "Olympic Steel Inc.", "company_sector": "Industrial Goods" }, "2": { "open": 40.4208, "high": 41.1223, "low": 39.9614, "close": 40.8802, "volume": 234567, "score": "98", "symbol": "XYZ", "company_name": "Example Corp.", "company_sector": "Industrial Goods" } }; // 转换后的数组,用来渲染表格 stockData: any[] = []; ngOnInit() { // 使用Object.values()把对象转成数组 this.stockData = Object.values(this.rawStockData); } }
2. 模板中渲染表格
接下来在组件的HTML模板里,用*ngFor遍历转换后的数组,把每个字段对应到表格的列中:
<div class="container"> <table class="table table-bordered"> <thead> <tr> <th>股票代码</th> <th>公司名称</th> <th>所属行业</th> <th>开盘价</th> <th>最高价</th> <th>最低价</th> <th>收盘价</th> <th>成交量</th> <th>评分</th> </tr> </thead> <tbody> <!-- 遍历stockData数组,渲染每一行 --> <tr *ngFor="let stock of stockData"> <td>{{ stock.symbol }}</td> <td>{{ stock.company_name }}</td> <td>{{ stock.company_sector }}</td> <td>{{ stock.open | number:'1.2-2' }}</td> <td>{{ stock.high | number:'1.2-2' }}</td> <td>{{ stock.low | number:'1.2-2' }}</td> <td>{{ stock.close | number:'1.2-2' }}</td> <td>{{ stock.volume | number }}</td> <td>{{ stock.score }}</td> </tr> </tbody> </table> </div>
补充说明
- 我用了Angular的
number管道来格式化价格(保留两位小数)和成交量(千分位分隔),让数据看起来更美观; - 如果你的数据是从API获取的,只需要把
rawStockData替换成API返回的数据即可,转换逻辑不变; - 要是需要样式美化,可以在组件的CSS里自定义表格样式,或者用Bootstrap的表格类(比如上面的
table table-bordered)。
内容的提问来源于stack exchange,提问作者Project
相关产品推荐
相关产品推荐

