admin管理员组文章数量:1415145
Using Angular 4, I need to display the average of some numbers. My ponent basically looks like this:
@Component({
selector: 'app-home',
templateUrl: './homeponent.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!
Using Angular 4, I need to display the average of some numbers. My ponent basically looks like this:
@Component({
selector: 'app-home',
templateUrl: './home.ponent.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!
Share Improve this question asked Aug 31, 2017 at 5:32 jdstein1jdstein1 1172 silver badges10 bronze badges2 Answers
Reset to default 4(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);
}
You have defined your function in the ngOnInit()
. And also remove function
word. Move out that function like
export class HomeComponent {
students:string[];
constructor(private studentsService: StudentsService) {}
ngOnInit() {
this.studentsService.getStudents().subscribe(students => {
...
});
}
doAvg (arr) : number {
var i, len=arr.length, average=0,
for (i=0;i<len;i++) {
average += arr[i];
}
return (average/arr.length);
}
}
You can also remove the obj
variable from the function, because it is not used and make your function return type number
.
本文标签: javascriptAngular 4 invoke method from templateStack Overflow
版权声明:本文标题:javascript - Angular 4: invoke method from template - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745218122a2648265.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论