Using Angular 4, I need to display the average of some numbers. My component basically looks like this:
@Component({
selector: 'app-home',
templateUrl: './home.component.html'
})
export class HomeComponent {
students:string[];
constructor(private studentsService: StudentsService) {}
ngOnInit() {
this.studentsService.getStudents().subscribe(students => {
...
})
function doAvg (arr) {
var i,
len=arr.length,
average=0,
obj={};
for (i=0;i<len;i++) {
average += arr[i];
}
return (average/arr.length);
}
}
}
My template has this markup (GPARecord is an array of floats):
<tr *ngFor="let student of students">
...
<td>{{ doAvg(student.GPARecord) }}</td>
</tr>
But I'm getting this error in the console:
ERROR TypeError: _co.doAvg is not a function
Help! Thanks!
(i)You do not need to have the keyword function, also with ts, use let , instead of var
(ii)Move outside of ngOnInit()
doAvg (arr) {
let i,
len=arr.length,
average=0,
obj={};
for (i=0;i<len;i++) {
average += arr[i];
}
return (average/arr.length);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With