Ilya Chernomordik Ilya Chernomordik - 1 year ago 254
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.index}`;

And this is my ngFor:

<div *ngFor="let foo of foos">

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.
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 Source

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) { = name; this.index = index; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download