Coeus Coeus - 20 days ago 5
JSON Question

Cannot read property of undefined in templates

In my component template, I'm getting output as [output:Output] but not what I wanted. I'm sending an object from a parent container using @Output

In my template when I try to bind

{{selectedMovDetail|json}}
the output is
{ "name": "The Walking Dead","rating":"8.6"}


But when I try to extract data using
{{selectedMovDetail['name']}}
I get the following error

enter image description here

When I tried to debug with Augury (chrome debug tool) I get

enter image description here

Now I'm confused how to extract the object values.
Any help regarding this is much appreciated

Answer

Use: selectedMovDetail?.name instead of selectedMovDetail['name'].

When you use the "elvis" operator, ?, in selecting your json keys, it will not throw an error if it can't find a specific key or the value has not been loaded yet (only in html).

For example in your case: selectedMovDetail.name exists after the template has been viewed so using ? before the . makes sure that name will be printed when it's loaded.