模板中Angular 2类的调用方法 [英] Calling method from a Angular 2 class inside template

查看:47
本文介绍了模板中Angular 2类的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个angular 2应用程序,该应用程序有一个名为User的类.该用户具有一个名为Deleted_at的属性,该属性为null或包含日期时间,显然,如果Deleted_at属性不为null,则删除该用户.这是我的user.ts文件的外观:

I have a angular 2 application that has a class called User. This user has a attribute called deleted_at that is either null or contains a datetime, obviously the user is deleted if the deleted_at property isn't null. This is how my user.ts file looks:

User.ts

export class User {
    id: number;
    email: string;
    created_at: string;
    first_name: string;
    last_name: string;
    deleted_at: any;

    name() {
        if (this.deleted_at === null) {
            return this.first_name;
        } else {
            return 'DELETED';
        }
    }
}

现在,我希望我可以在模板中以简单的行来命名:

Now I expected that I could just call name in my template with a simple line:

{{ user.name }}

这什么也不返回,如何在angular 2模板中调用某些函数?还是不允许这样做?

This however returns nothing, how can you call certain functions in the angular 2 template? Or isn't this allowed?

以清除内容,这是我在组件 user-list.component.ts 中使用的类User,可以处理多个用户在这个组件中.

to clear stuff up a bit, this is a class User that I am using in my component user-list.component.ts, multiple users are handled in this component.

推荐答案

您可以这样调用方法:

{{user.name()}} // instead of {{user.name}}

对于这种方法,您需要意识到您将丢失执行上下文(this).有关更多详细信息,请参见此问题:

For this approach you need to be aware that you will lose the execution context (this). See this question for more details:

或者您将方法定义为吸气剂,以便可以在模板中使用user.name:

Or you define your method as a getter so you can use user.name in your template:

get name() {
  if (this.deleted_at === null) {
    return this.first_name;
  } else {
    return 'DELETED';
  }
}

这篇关于模板中Angular 2类的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆