Having two classes professor
and student
:
- professor.ts
JavaScript
x
5
1
export class Professor {
2
id: number
3
name: string
4
}
5
- student.ts
JavaScript
1
9
1
import { Professor } from "./professor"
2
3
export class Student {
4
id: number
5
name: string
6
score: number
7
professor: Professor
8
}
9
To add up the scores of each student relative to his teacher I did:
JavaScript
1
15
15
1
sel: number[] = []
2
prof: Professor[]
3
stud: Student[]
4
totalScore: number
5
partial: number
6
var: boolean = false
7
8
total() {
9
const total = this.stud
10
.filter(c => this.sel.map(m => +m).includes(c.id))
11
.reduce((a, c) => a + c.score, 0);
12
this.totalScore = total
13
this.var = true
14
}
15
This is the HTML of the page:
JavaScript
1
21
21
1
<div name="professors" *ngFor="let p of prof; index as j">
2
{{ p.name }}
3
<select name="students{{j}}" [(ngModel)]="sel[j]" class="form-control">
4
<ng-container *ngFor="let s of stud; index as i">
5
<option *ngIf="s.professor.id === p.id" [value]="s.id">
6
{{ s.name }} <p>|</p>
7
{{ s.score }}
8
</option>
9
</ng-container>
10
</select>
11
<label></label>
12
</div>
13
14
<button type="submit" (click)="total()"
15
class="btn btn-primary">Go</button>
16
17
<div *ngIf="var">
18
<p>Total: {{totalScore}}<br>
19
<!--Partial sum: {{partial}}-->
20
</p>
21
</div>
How can I do a partial sum of the selections, assuming for example that I have 5 professor with 1 student for every professor, and want to add only the results of the first 3 student. This is the stackblitz: https://stackblitz.com/edit/angular-ivy-sjs7fg?file=src/app/app.component.ts
Advertisement
Answer
Change your total method to :-
JavaScript
1
9
1
total() {
2
const total = this.stud
3
.filter(c => this.sel.map(m => +m).includes(c.id))
4
.slice(0,3)
5
.reduce((a, c) => a + c.score, 0);
6
this.totalScore = total
7
this.variable = true
8
}
9
working stackblitz :- https://stackblitz.com/edit/angular-ivy-nkxswo?file=src/app/app.component.ts