【问题标题】:filter value of select to do a partial sum过滤 select 的值以进行部分求和
【发布时间】:2021-06-20 07:17:46
【问题描述】:

有两个类professorstudent

  • professor.ts
    export class Professor {
        id: number
        name: string
    }
  • student.ts
    import { Professor } from "./professor"
    
    export class Student {
        id: number
        name: string
        score: number
        professor: Professor
    }

将每个学生相对于老师的分数加起来:

sel: number[] = []
prof: Professor[]
stud: Student[]
totalScore: number
partial: number
var: boolean = false

total() {
const total = this.stud
    .filter(c => this.sel.map(m => +m).includes(c.id))
    .reduce((a, c) => a + c.score, 0);
    this.totalScore = total
    this.var = true
}

这是页面的 HTML:

<div name="professors" *ngFor="let p of prof; index as j">
              {{ p.name }}
              <select name="students{{j}}" [(ngModel)]="sel[j]" class="form-control">
                <ng-container *ngFor="let s of stud; index as i">
                  <option *ngIf="s.professor.id === p.id" [value]="s.id">
                    {{ s.name }} <p>|</p>
                    {{ s.score }} 
                  </option>            
                </ng-container>
              </select>
              <label></label>
            </div>

      <button type="submit" (click)="total()"
      class="btn btn-primary">Go</button>

      <div *ngIf="var">          
         <p>Total: {{totalScore}}<br>
         <!--Partial sum: {{partial}}-->
         </p>  
      </div>

我如何对选择进行部分求和,例如假设我有 5 位教授,每位教授有 1 位学生,并且只想添加前 3 位学生的结果。 这是堆栈闪电战: https://stackblitz.com/edit/angular-ivy-sjs7fg?file=src/app/app.component.ts

【问题讨论】:

  • 你能提供一个stackblitz吗?
  • @AakashGarg 是的,那个link
  • 你期望的输出是什么?
  • 例如前三个选择(丹尼尔、卢克、马克)的部分总和 = 6+8+3 = 17 不计算后续选择的总和

标签: javascript html arrays angular typescript


【解决方案1】:

将您的总方法更改为:-

total() {
const total = this.stud
    .filter(c => this.sel.map(m => +m).includes(c.id))
    .slice(0,3)
    .reduce((a, c) => a + c.score, 0);
    this.totalScore = total
    this.variable = true
}

工作堆栈闪电战:- https://stackblitz.com/edit/angular-ivy-nkxswo?file=src/app/app.component.ts

【讨论】:

    猜你喜欢
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 2015-09-17
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多