【发布时间】:2016-06-09 01:28:44
【问题描述】:
我想从 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 angular