Another Angular2 Quicky for today ;) Angular2 introduces the Elvis operator ?. which can be used within templates.

CoffeeScript Developers (Note: I ) may know this as “Existential Operator” which can easily be used to check if a variable has a value.

In combination with *ngFor and *ngIf this makes a good toolbelt for rapidly building UIs within ng2 Apps.

elvis in tha house

The documentation at https://angular.io/docs/ts/latest/guide/template-syntax.html#!#expression-operators gives you a few examples how to use the Elvis operator.

The good thing about the Elvis operator is that you can use it in chains like shown below

<span>{{a?.b?.c?.d?.name}}</span>

But that’s only half of the truth. Only in a few situations you want to just display nothing. Most of the time you want to provide a kind of fallback value.

<span>Thank you for {{transaction?.operation?.caption}}
  {{transaction.items.length+1}} items
</span>

Would generate the following output

@Component({})
export class MyComponent {
  public transaction: any = {
    items = [{ /* ... */ }],
    operation = { caption: 'buying', ..}
  }
}

// output
'Thank you for buying 100 items'

or

@Component({})
export class MyComponent {
  public transaction: any = {
    items = [{ /* ... */}],
    operation = null
  }
}

// generated output:
'Thank you for 100 items'

This isn’t the message you want to display to your users, instead you want to provide a fallback in the UI. For sure you can use *ngIf to remove the entire span, but you can also fix it using the logical or || operator in conjunction with the Elvis operator. Update the sample HTML to match the following

<span>Thank you for {{transaction?.operation?.caption || 'buying' }}
  {{transaction.items.length+1}} items
</span>

I’ve created a small sample here which uses the combination of *ngFor, *ngIf and ? the Elvis operator