gpt4 book ai didi

angular - ngFor 迭代对象数组并计算数组属性的长度

转载 作者:行者123 更新时间:2023-12-04 14:40:42 26 4
gpt4 key购买 nike

我正在 Angular 6 中开发一个 Web 应用程序。我从 Firebase 收到一组对象,并尝试使用 ngFor 向用户显示详细信息。我的对象数组是这样的:

export interface Competition {
createdAt: Date;
sessions: Session[];
}

export interface Session {
date: Date;
program: Program[];
events: Event[];
}

export interface Program {
name: string;
}

export interface Event {
name: string;
}

在我正在做的模板中:

<ng-container *ngFor="let competition of competitions; index as i">
<h3>{{competition.name}}</h3>
{{competition.sessions[i].program.length}}
{{competition.sessions[i].events.length}}
</ng-container>

read property 'program' of undefined, read property 'events' of undefined

我已经尝试过:

{{competition[i].sessions[i].program.length}}
{{competition.sessions[i].program.length}}
{{competition[i].sessions[i].program[i].length}}

我的目标是显示节目事件的长度。

最佳答案

您迭代competitions数组,但尝试获取competition.sessions[i]。你需要这样的东西:

<ng-container *ngFor="let competition of competitions; index as i">
<h3>{{competition.name}}</h3>
<div *ngFor="let session of competition.sessions">
{{session.program.length}}
{{session.events.length}}
</div>
</ng-container>

如果你想获得比赛的场次和事件总数,你应该在你的ts文件中计算它们

this.competitionResults = this.competitions
.map(competition => competition.sessions
.reduce((res, session) =>
({
programLength: res.programLength + session.program.length,
eventLength: res.eventLength + session.events.length,
}), {
programLength: 0,
eventLength: 0,
}))
)

和 HTML:

<ng-container *ngFor="let competitionResult of competitionResults">
{{ competitionResult.programLength }}
{{ competitionResult.eventLength}}
</ng-container>

关于angular - ngFor 迭代对象数组并计算数组属性的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54770488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com