AngularJs2 : display JSON object in a template

1 view
Skip to first unread message

herve.be...@gmail.com

unread,
Sep 9, 2016, 2:47:14 AM9/9/16
to Angular2
Hi,

I have a JSON object and i want to display it in a view.

<div >{{ pat | json }}</div>

display 
 { "id": 1, "label": "pat 1"}

<div >{{ pat }}</div>
display 

[object Object]

But if i type

<div >{{ pat.id }}</div>

I have the following error
ORIGINAL EXCEPTION: TypeError: Cannot read property 'id' of undefined

My question : How to display the properties of my JSON object ?

NB : if i have une list of Json object [{ "id": 1, "label": "pat 1"},{ "id": 2, "label": "pat 2"}]
the following code works 
<li *ngFor="let pat of pats" >
  {{
pat.id }} - {{ pat.label}}
</li>
display 
1 - pat 1
2 - pat 2

Bruno Barthez

unread,
Sep 9, 2016, 6:10:45 AM9/9/16
to Angular2
You must use the "?." operator.
<div >{{ pat?.id }}</div>
The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. 
Reply all
Reply to author
Forward
0 new messages