从模板内的 Angular 2 类调用方法
我有一个 angular 2 应用程序,它有一个名为 User
的类.这个用户有一个名为 deleted_at
的属性,它要么是 nul
l 要么包含一个日期时间,显然如果 deleted_at
属性不是空代码>.这是我的 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 nul
l 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:
或者您将方法定义为 getter,以便您可以在模板中使用 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';
}
}