Ilya Chernomordik Ilya Chernomordik - 1 month ago 32
TypeScript Question

Cannot call a function on an element inside ngFor Angular2

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.

Answer

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; }