问题
I have a very simple class
export class Foo {
name: string;
index: number;
toFullString(): string {
return `${this.name} | ${this.index}`;
}
}
And this is my ngFor:
<div *ngFor="let foo of foos">
{{foo.toFullString()}};
</div>
And what I get is that method does not exist in the console:
self.context.$implicit.toFullString is not a function
I cannot figure out what's wrong in here. foo.name
works fine and outputs all the elements. I suppose that the way typescript adds methods to an object messed up this for angular 2, but cannot figure out what to do.
回答1:
My guess is that you are not newing up the class, but doing a cast or conversion.
You need to do a new Foo(nameParam, indexParam)
with an associated constructor taking the name and index constructor(public name, public index) { this.name = name; this.index = index; }
来源:https://stackoverflow.com/questions/40510795/cannot-call-a-function-on-an-element-inside-ngfor-angular2