Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 typescript how to get object properties to display in template

I am learning angular2 and typescript and wondering why I can not access property values of the object in my template.

My component:

export class Farm{

    data:JSON;
    id: any;

    constructor(private nextService: NextService, navParams: NavParams){
        this.id = navParams.get("param1");

    }

    getFarmDetails(){

        this.data = this.nextService.fetchData(this.id)
        console.log(this.data)
    }
}

where console.log(this.data) gives me Object {id: 1, name: "Leanne Graham", username: "Bret", email: "[email protected]", address: Object…}

In my template I have

<div>
    {{data}}
</div>

which outputs on my screen as [object Object]

How can I instead output properties like email or username?

UPDATE: If I do like {{data.email}} I get following error:

enter image description here

like image 422
Thinker Avatar asked Jun 28 '16 09:06

Thinker


1 Answers

You can access those properties as you would in javascript.

For example:

{{data.email}} 

If the data is retrieved asynchronously you can use the elvis operator ?. to avoid the errors while data is null.

{{data?.email}}
like image 96
toskv Avatar answered Oct 29 '22 22:10

toskv