如何在Angular 12的HTML中使用*ngFor遍历对象键?
Angular 12模板中用*ngFor遍历对象键的实现方案
针对你提供的学生数据结构,这里给出两种实用的实现方法:
方法一:使用Angular自带的KeyValuePipe(推荐)
Angular内置的KeyValuePipe可以直接把对象转换为键值对数组,无需在组件里额外处理逻辑,适合快速实现。
模板代码示例
<!-- 假设你的组件中已将数据赋值给了studentData变量 --> <div *ngFor="let studentItem of studentData.data[0] | keyvalue:false"> <p><strong>学生ID:</strong> {{ studentItem.key }}</p> <p><strong>姓名:</strong> {{ studentItem.value.name }}</p> <p><strong>出勤状态:</strong> {{ studentItem.value.present ? '已出勤' : '未出勤' }}</p> <hr> </div>
- 说明:
keyvalue:false用来关闭默认的按键排序,保持对象原本的键顺序;如果不需要保留原顺序,可以省略:false。 - 如果
data数组包含多个分组对象,需要先遍历分组:
<div *ngFor="let group of studentData.data"> <div *ngFor="let studentItem of group | keyvalue:false"> <!-- 学生信息渲染代码同上 --> </div> </div>
方法二:在组件中用Object.keys()处理
如果你更倾向于在组件层处理数据结构,可以用Object.keys()提取对象的键数组,再在模板中遍历。
组件代码示例
import { Component } from '@angular/core'; @Component({ selector: 'app-student-list', templateUrl: './student-list.component.html', styleUrls: ['./student-list.component.css'] }) export class StudentListComponent { studentData = { "data": [ { "student1": { "name": "Jhon", "present": false }, "student2": { "name": "Bill", "present": true }, "student3": { "name": "Keth", "present": true }, "student4": { "name": "Anna", "present": true }, "student5": { "name": "Vendy", "present": false }, "student6": { "name": "Tim", "present": true }, "student7": { "name": "Ron", "present": false } } ] }; // 获取学生对象的键数组 getStudentIds(): string[] { return Object.keys(this.studentData.data[0]); } }
模板代码示例
<div *ngFor="let studentId of getStudentIds()"> <p><strong>学生ID:</strong> {{ studentId }}</p> <p><strong>姓名:</strong> {{ studentData.data[0][studentId].name }}</p> <p><strong>出勤状态:</strong> {{ studentData.data[0][studentId].present ? '已出勤' : '未出勤' }}</p> <hr> </div>
内容的提问来源于stack exchange,提问作者Anna
相关产品推荐
相关产品推荐

