组件:
export class PersonalRecordsComponent implements OnInit {
currentUser = [];
userRecords = [];
movements = [
"Back Squat",
"Bench Press",
"Clean",
"Clean & Jerk",
"Custom Movement",
"Deadlift",
"Front Squat",
"Jerk",
"Power Clean",
"Power Snatch",
"Push Press",
"Snatch",
"Strict Press"
];
constructor(private afService: AF) {
// Get current user details.
afService.getCurrentUserInfo().then(currentUserDetails => {
this.currentUser.push(currentUserDetails);
}).then(() => {
for(let movement of this.movements) {
this.afService.getRecords(movement, this.currentUser[0].userID).subscribe((data) => {
this.userRecords.push(data);
});
}
}).then(()=>{
console.log(this.userRecords)
})
}
HTML:
<ng-container *ngFor="let record of userRecords">
<div class="list-athletes">
<div class="list-athletes-details">
<p>{{ record.movement }} - {{ record.weight }}</p>
</div>
<div class="list-athletes-actions">
<div class="btn-group">
</div>
</div>
</div>
</ng-container>
上面的代码输出13 <div>
,这是正确的,但由于*ngFor="let record of userRecords"
它们是空的。如果我改为在{ngFor循环中写*ngFor="let record of userRecords[0]"
,它会输出正确的数据,但仅显示第一个数组。
我的问题是:如何在不编写13个*ngFor
循环的情况下为13个阵列中的每个阵列输出正确的数据,例如:
*ngFor="let record of userRecords[0]"
*ngFor="let record of userRecords[1]"
*ngFor="let record of userRecords[2]"
等
这些数组中的每一个都可以包含多个对象。
[
[
{
"comments": "Back squat comment alpha",
"movement": "Back Squat",
"userID": "wDHZv3OL55SIymHkhMUejNleNkx1",
"weight": "365"
},
{
"comments": "Back squat comment bravo",
"movement": "Back Squat",
"userID": "wDHZv3OL55SIymHkhMUejNleNkx1",
"weight": "325"
}
],
[],
[],
[],
[],
[],
[
{
"comments": "Front squat comment alpha",
"movement": "Front Squat",
"userID": "wDHZv3OL55SIymHkhMUejNleNkx1",
"weight": "315"
}
],
[],
[],
[],
[],
[],
[]
]
答案 0 :(得分:1)
答案 1 :(得分:1)
作为一个想法,为什么不使用*ngFor
运行嵌入式*ngIf
循环以确保数组不为空?所以你的HTML看起来像......
<ng-container *ngFor="let lift of userRecords">
<div *ngIf="records(lift)">
<div *ngFor="let record of lift">
<div class="list-athletes">
<div class="list-athletes-details">
<p>{{ record.movement }} - {{ record.weight }}</p>
</div>
<div class="list-athletes-actions">
<div class="btn-group"></div>
</div>
</div>
</div>
</div>
</ng-container>
并且您要为组件添加一个名为records
的方法,如下所示:
public records(lifts: any[]): boolean {
return (lifts.length > 0) ? true : false;
}
此功能只会检查是否有要显示的记录。
答案 2 :(得分:1)
你需要有两个 ngFor
,因为记录也是一个数组,
<ng-container *ngFor="let record of userRecords">
<div *ngFor="let reco of record">
还要确保您在 CommonModule
app.module.ts