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

RRG*_*T19 2 angular-template angular-directive ngfor angular

我在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;
}
Run Code Online (Sandbox Code Playgroud)

在我正在做的模板内:

<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>
Run Code Online (Sandbox Code Playgroud)

读取未定义的属性"program",读取未定义的属性"events"

我试过了:

{{competition[i].sessions[i].program.length}}
{{competition.sessions[i].program.length}}
{{competition[i].sessions[i].program[i].length}}
Run Code Online (Sandbox Code Playgroud)

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

Iva*_*van 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>
Run Code Online (Sandbox Code Playgroud)

如果您想获得比赛的会话和活动总数,您应该在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,
           }))
   )
Run Code Online (Sandbox Code Playgroud)

和HTML:

<ng-container *ngFor="let competitionResult of competitionResults">
   {{ competitionResult.programLength }}
   {{ competitionResult.eventLength}}
</ng-container>
Run Code Online (Sandbox Code Playgroud)