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

问题描述 投票:2回答:2

我在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>

读取未定义的属性“program”,读取未定义的属性“events”

我试过了:

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

我的目标是显示programevents的长度。

angular angular-directive ngfor angular-template
2个回答
5
投票

你迭代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>

0
投票

更改定义以直接定义字符串数组:

export interface Session {
  date: Date;
  program: string[];
  events: string[];
}
© www.soinside.com 2019 - 2024. All rights reserved.