Monday, 28 May 2018

Angular - The safe navigation operator ( ?. ) and null property paths

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.
The current hero's name is {{currentHero?.name}}
What happens when the following data bound title property is null?
The title is {{title}}
The view still renders but the displayed value is blank; you see only "The title is" with nothing after it. That is reasonable behavior. At least the app doesn't crash.
Suppose the template expression involves a property path, as in this next example that displays the name of a null hero.
The null hero's name is {{}}
JavaScript throws a null reference error, and so does Angular:
TypeError: Cannot read property 'name' of null in [null].
Worse, the entire view disappears.
This would be reasonable behavior if the hero property could never be null. If it must never be null and yet it is null, that's a programming error that should be caught and fixed. Throwing an exception is the right thing to do.
On the other hand, null values in the property path may be OK from time to time, especially when the data are null now and will arrive eventually.
While waiting for data, the view should render without complaint, and the null property path should display as blank just as the title property does.
Unfortunately, the app crashes when the currentHero is null.
You could code around that problem with *ngIf.
<!--No hero, div not displayed, no error -->
<div *ngIf="nullHero">The null hero's name is {{}}</div>
You could try to chain parts of the property path with &&, knowing that the expression bails out when it encounters the first null.
The null hero's name is {{nullHero &&}}
These approaches have merit but can be cumbersome, especially if the property path is long. Imagine guarding against a null somewhere in a long property path such as a.b.c.d.
The Angular safe navigation operator (?.) is a more fluent and convenient way to guard against nulls in property paths. The expression bails out when it hits the first null value. The display is blank, but the app keeps rolling without errors.
<!-- No hero, no problem! -->
The null hero's name is {{nullHero?.name}}
It works perfectly with long property paths such as a?.b?.c?.d.

No comments:

Post a Comment