Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4: invoke method from template

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!

like image 357
jdstein1 Avatar asked Dec 08 '25 08:12

jdstein1


1 Answers

(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);
    }
like image 96
Sajeetharan Avatar answered Dec 09 '25 22:12

Sajeetharan