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

标签 angular angular-directive ngfor angular-template

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

相关文章:

angularjs - 隐藏时从 $scope 中删除所有 ng-model 变量

typescript - ionic2 中的导入指令 - ng2-qrcode

angular - 如何使用 *ngFor 迭代对象键?

java - OAuth token 在浏览器上未经授权

javascript - Chrome 不透明度过渡 z-index 问题

javascript - 一旦文本区域变得可见,就转换它的值

html - Angular4/HTML - 使用 *ngFor 的多个是或否单选组

angular - 从 ngrx 选择器获取数据

c# - 使用 .net、angular 和 electron 的桌面应用程序

javascript - *ng用于数组的动态字符串插值