I came across an oddity with Angular2 development.  I had a case where I was pulling data into my application.  The data came in as a list of objects.  I wanted to get a count on these objects returned and I wanted to display that count into a view.

Normally in a language like Ruby, Groovy or Python you would use a variation of a method like length.  Sure enough, there was such a method available in Angular2.

So I wrote something like this:

{{ books.length }}

However, this returned an error in the console:

Cannot read property ‘length’ of undefined

The solution here was to turn this into an Elvis Operator ?., like so: (( See issue referenced at https://github.com/angular/angular/issues/1914)) ((Also see https://github.com/angular/angular/issues/791))

{{ books?.length }}

Why is this?  It’s due to lazy loading and asynchronous.  At the initial load, the data for books may not be available – it is temporarily undefined.  In other languages, the page load may halt and wait while the data is returned and then displayed.  Since Angular2 is using Observables (data that is subscribed to and loaded asynchronously), the value may be undefined until it’s fully loaded (after initial page load.)

The Evils Operator

My first interaction with the Elvis Operator was in Groovy.  In the Groovy language this operator acts as a ternary operator –  meaning we have a default value: Example groovy Elvis Operator:

displayName = user.name ?: ‘Anonymous’

source: http://docs.groovy-lang.org/latest/html/documentation/index.html#_elvis_operator

In Angular2 the Elvis Operator perhaps is doing something similar, but the documentation reads differently. It seems that in Angular we are using the Elvis Operator to temporarily set a value as defined for the purpose of lazy loading.  In other words, books.length would fail because we are rendering the page before we have the value for books returned.  But if we do books?.length, then we are setting a temporary state for books, and once it’s loaded we grab its length. (( For more information on Angular2’s Elvis Operator, see http://www.syntaxsuccess.com/viewarticle/elvis-operator-in-angular-2.0))


No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *