【问题标题】:Binding to a function result of a class in Angular绑定到Angular中类的函数结果
【发布时间】:2018-06-24 10:47:15
【问题描述】:

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

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

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

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

很遗憾,我的浏览器出现错误:

ERROR TypeError: "_v.context.$implicit.getPoints is not a function"

我的团队类如下所示:

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

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

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

【问题讨论】:

    标签: angular


    【解决方案1】:

    您以错误的方式声明您的功能。

    不是:

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

    应该是:

    getPoint() {
        return "Test";
    }
    

    这个解决方案怎么样?希望对您有所帮助!

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

    您正在尝试执行的操作称为 字符串插值

    LIVE DEMO

    【讨论】:

    • 可悲的是,它仍然是一个类似的错误。错误类型错误:“_co.getPoints 不是函数”
    • @HoppyKlaus 我为您创建了一个现场演示,我没有收到任何错误。希望能帮助到你。这是链接:stackblitz.com/edit/…
    • @HoppyKlaus 您的问题是您以错误的方式声明您的功能。请看看我更新的解决方案。
    • 即使按照你的方式声明了函数,我也得到了它。错误类型错误:“_v.context.$implicit.getPoints 不是函数”
    • @HoppyKlaus 我不确定您的应用程序的结构是什么,但正如我在现场演示中向您展示的那样。我没有收到任何错误。
    【解决方案2】:

    因为数组中是数组,所以不能运行,如果你不能为 {{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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 2017-08-17
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 2013-12-23
      相关资源
      最近更新 更多