import {
Component,
OnInit
} from "@angular/core";
import {
MarkService
} from "../app/services/marks.service";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
title = "my-test";
public students = [];
allStudents: any = [];
average: any = [];
constructor(private _marksService: MarkService) {}
ngOnInit() {
this._marksService.getMarks().subscribe(data => (this.students = data));
}
calHandle(i) {
var data = this.students;
this.average = Object.values(data).reduce(
(avg, {
values
}, _, {
length
}) => avg + values / length,
0
);
}
}
<table border="1">
<tr>
<th>Name</th>
<th>Jan</th>
<th>Feb</th>
<th>March</th>
<th>April</th>
<th>action</th>
<th>Average</th>
<!-- </tr> -->
<tbody *ngFor="let item of students; let i = index;">
<tr>
<td>{{item.name}}</td>
<td>{{item.jan}}</td>
<td>{{item.feb}}</td>
<td>{{item.march}}</td>
<td>{{item.April}}</td>
<td><button (click)="calHandle(i)">calculate</button></td>
<td>{{average}}</td>
</tr>
</tbody>
</table>
<!--
json data
[
{"name": "josh", "jan":20,"feb":32, "march":"50", "April":45},
{"name": "peter", "jan":20,"feb":32, "march":"50", "April":45},
{"name": "gorge", "jan":20,"feb":32, "march":"50", "April":45}
]
-->
I have created a code snippet to calculate the average student scores upon clicking a button. However, when I click the "calculate" button, the result is displayed as "NaN". I am seeking advice on how to ensure only numerical values are used to prevent this error and also how to properly display the average score for each individual student on button click.