简体   繁体   中英

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]

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 : "" }} {{ 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM