Angular中如何遍历嵌套JSON对象并在模板用*ngFor渲染
在Angular中遍历嵌套JSON对象的解决方案
假设你的client.json结构如下:
{ "T001": { "name": "admin", "desc": "主隧道" }, "T002": { "name": "guest", "desc": "访客隧道" } }
步骤1:将嵌套对象转换为可遍历的数组
在组件中,利用Object.entries()方法把JSON对象的键值对转为数组,这样就能用*ngFor遍历了。
直接导入JSON文件的情况
import { Component, OnInit } from '@angular/core'; // 导入本地JSON文件 import clientData from './client.json'; @Component({ selector: 'app-tunnel-list', templateUrl: './tunnel-list.component.html' }) export class TunnelListComponent implements OnInit { // 存储键值对数组,类型为[隧道ID, 属性对象] tunnelEntries: [string, any][] = []; ngOnInit(): void { // 转换为可遍历的数组 this.tunnelEntries = Object.entries(clientData); } }
通过HTTP读取JSON文件的情况
如果是从assets目录读取,用HttpClient请求后再转换:
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-tunnel-list', templateUrl: './tunnel-list.component.html' }) export class TunnelListComponent implements OnInit { tunnelEntries: [string, any][] = []; constructor(private http: HttpClient) {} ngOnInit(): void { this.http.get('/assets/client.json').subscribe((data: any) => { this.tunnelEntries = Object.entries(data); }); } }
步骤2:在HTML模板中遍历渲染
直接使用*ngFor遍历转换后的数组,通过索引获取隧道ID和属性:
<div *ngFor="let entry of tunnelEntries"> Tunnel: {{ entry[0] }},Name: {{ entry[1].name }} </div>
可选:转换为更清晰的对象结构
如果觉得数组索引不够直观,可以把键值对映射为结构化对象:
// 在组件的ngOnInit中替换转换逻辑 this.tunnelEntries = Object.entries(clientData).map(([tunnelId, props]) => ({ tunnelId, ...props }));
对应的模板代码可以写成:
<div *ngFor="let tunnel of tunnelEntries"> Tunnel: {{ tunnel.tunnelId }},Name: {{ tunnel.name }} </div>
内容的提问来源于stack exchange,提问作者corol
相关产品推荐
相关产品推荐

