We build a dashboard-like interface and frequently receive generic objects with optional fields, such as the event
object below. event
may not be defined at the time the template is loaded, and it may or may not have a daysRemaining ?: number
parameter; if it is set, it may be 0
.
To ensure that a 0
value is actually printed in the above scenario, we use this pattern:
<div *ngIf="event?.daysRemaining?.toString().length > 0">
{{event.daysRemaining}} days
</div>
(The .toString()
is necessary because Property 'length' does not exist on type 'number'.)
Our object tree can be much deeper than the above example. Where we can wrap common a parent tree in an <ng-container>
's *ngIf
, we do, but we rarely can.
There must be a more elegant way to do this, especially with regard to needing to call .toString()
on virtually every optional number
.
This seems more efficient:
<div>
{{event?.daysRemaining + ' days'}}
</div>
But has the drawback that if we need to optionally add things to the <div>
(such a color: red
when daysRemaining < 0
), we still need all the checks.