Q . angular2: Error: TypeError: Cannot read property '…' of undefined

Brad Johnson. asked, Sep 02 ' 2017

I am printing some json data in my html template But getting some error in my console.

Please suggest why this is happening?

Code :

<div class="w3-col m8">
   <ng-template [ngIf]="qnaData.tags.length > 0">
       <a class="w3-button w3-teal" *ngFor="let tag of qnaData.tags">
           {{tag.tag}}
       </a>
   </ng-template>
</div>

 

Error : 


ERROR TypeError: Cannot read property 'tags' of undefined
    at Object.View_QuestionComponent_0._co [as updateDirectives] (QuestionComponent.html:32)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13075)
    at checkAndUpdateView (core.es5.js:12255)
    at callViewAction (core.es5.js:12620)
    at execComponentViewsAction (core.es5.js:12552)
    at checkAndUpdateView (core.es5.js:12261)
    at callViewAction (core.es5.js:12620)
    at execEmbeddedViewsAction (core.es5.js:12578)
    at checkAndUpdateView (core.es5.js:12256)
    at callViewAction (core.es5.js:12620)
  • angular2
  • angular2-console-error

1 Answers

That's because tags is undefined at the moment of the template rendering.

You can use safe navigation operator (?) to "protect" template until HTTP call is completed:

{{abc?.xyz?.name}}

You can read more about safe navigation operator here.

Update:

Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf directive to overcome this problem:

<div *ngIf="arr && arr.length > 0">
    {{arr[0].name}}
</div>

Read more about NgIf directive here.

Leave a Ansewer