5

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

1 Answer 1

27

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}}
Sign up to request clarification or add additional context in comments.

3 Comments

I tried that but it throws error: ORIGINAL EXCEPTION: TypeError: Cannot read property 'email' of undefined
Thank you! You just saved me another hour of debugging issues and facepalming. The "elvis" operator is also called the "safe navigation operator" sometimes
@SoFLy that's what SO is for. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.