How to fix Error: TypeError: Cannot read property ‘…’ of undefined with Angular?

Sometimes, we want to fix Error: TypeError: Cannot read property ‘…’ of undefined with Angular.

In this article, we’ll look at how to fix Error: TypeError: Cannot read property ‘…’ of undefined with Angular.

How to fix Error: TypeError: Cannot read property ‘…’ of undefined with Angular?

To fix Error: TypeError: Cannot read property ‘…’ of undefined with Angular, we should make sure the variable we’re rendering is defined.

For instance, we write

{{ foo?.bar?.name }}

to use the safe navigation operator if foo and bar are objects.

And if we want to do the same check for arrays, we can use *ngIf by writing something like

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

We use arr && arr.length > 0 to make sure arr is defined and it has length bigger than 0.

Conclusion

To fix Error: TypeError: Cannot read property ‘…’ of undefined with Angular, we should make sure the variable we’re rendering is defined.