绑定到Angular中的类的函数结果

时间:2018-06-24 01:52:06

标签: angular

在Angular中,绑定到类变量很简单,例如:

<tr *ngFor="let team of teams">
    <th scope="row">{{team.name}}</th>

但是我想从类而不是像这样的变量绑定到函数:

<td>{{ team.getPoints() }}</td>

不幸的是,我在浏览器中遇到错误:

  

错误TypeError:“ _ v.context。$ implicit.getPoints不是函数”

我的团队班级看起来像这样:

export class Team {
    name: string;
    results: Array<Result>;

    getPoints = function() {
        return 0; //STUB: to be calculated
    };
}

我对当前的Angular没有太多经验,但这对我来说应该很简单。为什么我不能绑定到该功能?

2 个答案:

答案 0 :(得分:0)

您以错误的方式声明了函数。

不是:

getPoints = function() {
    return 0; //STUB: to be calculated
};

应该是:

getPoint() {
    return "Test";
}

该解决方案如何?希望对您有帮助!

<td>{{ getPoints() }}</td>

您要尝试的操作称为 字符串插值

LIVE DEMO

答案 1 :(得分:0)

因为数组是数组,所以不起作用,如果您不能{{team.getPoints()}},则只能{{team.name}} 您可以尝试使用以下代码!

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
     check : string;
    games : [{
        game: string,
        platform : string,
        release : string
    }];
    constructor(){
        this.check="OK";
        this.games = [{
            game : "Deus Ex: Mankind Divided",
            platform: " Xbox One, PS4, PC",
            release : "August 23"
        },
        {
            game : "Hue",
            platform: " Xbox One, PS4, Vita, PC",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        },
        {
            game : "The Huntsman: Winter's Curse",
            platform: "PS4",
            release : "August 23"
        }];

    };
    getPoint(){
       return this.check;
    }
}
<tr *ngFor="let game of games; let i = index">
   <td> {{game.game}}</td>
   <td>{{getPoint()}}</td>

</tr>