无法在 ngFor Angular2 中的元素上调用函数

Cannot call a function on an element inside ngFor Angular2

我有一个很简单的class

export class Foo {

    name: string;

    index: number;

    toFullString(): string {
        return `${this.name} | ${this.index}`;
    }
}

这是我的 ngFor:

<div *ngFor="let foo of foos">
    {{foo.toFullString()}};
</div>

我得到的是控制台中不存在该方法:

self.context.$implicit.toFullString is not a function

我不知道这里出了什么问题。 foo.name 工作正常并输出所有元素。我想打字稿向对象添加方法的方式搞砸了 angular 2,但不知道该怎么做。

我猜你不是在更新 class,而是在进行强制转换或转换。

你需要做一个new Foo(nameParam, indexParam),关联的构造函数采用名称和索引constructor(public name, public index) { this.name = name; this.index = index; }