我想从 angular2 模板调用 typescript 属性。如果我在循环中调用一个对象的属性,我就不能这样做。如果没有循环,代码可以正常工作。
Calling method from a Angular 2 class inside template如果没有循环,这个问题解决了这个问题。
请找到 Plunker here .
import {Component} from '@angular/core'
export class User {
id: number;
mail: string;
created_at: string;
first_name: string;
last_name: string;
deleted_at: any;
// if I call {{user.name}} nothing gets printed.
get name() {
return "My name is:" + this.first_name;
}
}
@Component({
selector: 'my-app',
template: `
<ion-list *ngFor="let user of users">
<div>{{user.first_name}}</div>
</ion-list>
`
})
export class App {
users: User[];
constructor() {
this.users = [ {first_name:"Jagan"}, {first_name:"Nath"} ];
}
}
更新
这是一段代码。下面给出了工作和非工作版本。
//our root app component
import {Component, Input} from '@angular/core'
import { MyComponent } from './my-component';
export class User {
first_name : string;
get name() {
return "Name:" + this.first_name;
}
}
@Component({
selector: 'my-app',
template: `
<div>
{{user.first_name}}
</div>
`,
directives: [ MyComponent ]
})
export class App {
constructor() {
let str = "{ \"first_name\" : \"Jagan\" }";
this.user = JSON.parse(str) as User;
}
}
//这行不通。
/* @Component({
selector: 'my-app',
template: `
<div>
{{user.name}}
</div>
`,
directives: [ MyComponent ]
})
*/
最佳答案
更新
在更新后的代码中,您只是告诉 TypeScript 您现在拥有的任何 JSON 对象都应被视为 User
对象。 TypeScript 会很乐意为您解析它,但在运行时您实际上没有 User
对象,正如您无法访问 name
方法这一事实所证明的那样。您可以通过将对象打印到控制台来自己检查对象:console.log(this.user)
。您将看到它打印 Object {first_name: "Jagan"}
。这显然不是 User
对象。
我建议在 User
上创建一个接受 JSON 参数的构造函数,并让 User
对象使用此 JSON 配置自身。我创建了一个 Plunker 供您查看实际想法:Plunker - updated
User
将获得一个接受 JSON 配置的构造函数(如果需要,您甚至可以输入):
constructor(config: any) {
this.first_name = config.first_name;
}
并且在构建User
时,您在其构造函数中传递配置:
let obj = { first_name: 'Jagan' };
this.user = new User(obj);
原创
当您创建一个new User
时,您应该使用构造函数来设置新User
对象的参数。在当前情况下,您只是通过键入 {first_name: "name"}
将一些新对象(甚至不是 User
对象)推送到 users
数组>。您可以通过将 users
数组打印到您的控制台(即:console.log(users)
)来检查您当前的代码。
我在 User
上创建了一个带有构造函数的 Plunker:Plunker .
User
将获得一个构造函数:
constructor(first_name: string) {
this.first_name = first_name;
}
现在调用 new User
需要一个新参数,first_name
:
this.users = [ new User("Jagan"), new User("Nath") ];
关于typescript - 在angular2中调用typescript getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37715500/