Luke Xu
Luke Xu

Reputation: 2440

I can't access a controller property in my angular2 view

I have a interface

export interface IInterview {
    id: number;
    title: string;
    body: string;
}

and when I do console.log(interview) in my controller it shows that I have

Object {title: "I SEE SOMETHING", id: 2, body: "THIS IS SO AWESOME HUEHUEHUEHUE"}

But when I go to my views and I do {{ interview.body }} I get an error saying

Cannot read property 'body' of undefined in [ {{ interview.body }}

And when I try {{ interview }} it just says [object Object]

Upvotes: 1

Views: 116

Answers (1)

acdcjunior
acdcjunior

Reputation: 135772

Try using:

{{ interview?.body }}

Reason:

The interview property of your component is probably undefined at the first moment angular tries to render the view.

The elvis safe navigation operator (?.) ensures that angular will only attempt to render the variable if it is not null.

If works roughly like {{ interview ? interview.body : "" }}.

You can find out more about it at the official docs: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#safe-navigation-operator or at the cheatsheet.

Upvotes: 2

Related Questions