Cannot call a function on an element inside ngFor Angular2

徘徊边缘 提交于 2019-12-11 06:43:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!