I would like to call a typescript property from angular2 template. I can't do that if I call the property of an object in a loop. If there is no loop, the code works fine.
Calling method from a Angular 2 class inside template this question addresses the problem if there is no loop.
Please find the 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"} ];
}
}
Update
Here is a piece of code. Both working and not working version is given below.
//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;
}
}
// This does not work.
/* @Component({
selector: 'my-app',
template: `
<div>
{{user.name}}
</div>
`,
directives: [ MyComponent ]
})
*/