Jonas Arcangel
Jonas Arcangel

Reputation: 1925

Cannot read property 'MyProperty' of undefined

In my Angular2 template, I have the following binding:

{{Stringify(result)}}
{{result.MyProperty}}

Stringify is a function that returns JSON.stringify of the input object. The Stringify function returned a JSON string that shows the name and value of MyProperty.

However, the second line returns a

TypeError. Cannot read property 'MyProperty' of undefined in {{result.MyProperty}}.

JSON.stringify clearly shows that this property / field exists, so why am I getting an error?

Upvotes: 2

Views: 305

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657248

If it's there it can be accessed and JS wouldn't throw

Try instead

{{result?.MyProperty}}

maybe Angular makes an attempt to access result.MyProperty before result has a value while Stringify(result) doesn't choke on null. When result is updated in the meantime (maybe because the value was received from the server, the view would update before you can recognized that an empty string was shown before.
Your question doesn't provide enough context to know.

See also

Upvotes: 1

Related Questions