mattchue
mattchue

Reputation: 121

Angular ternary operators

I'm attempting to use a ternary operator to set up a portion of my template:

account.accountType === "" ? "" : "Type: " + account.accountType

This code snippet should leave out the Type label if it is null. However, the type label is always present:

Evaluates to true: Type:
Evaluates to false: Type: {{ account.accountType }}

My desired behavior would be:

Evaluates to true: ""
Evaluates to false: Type: {{ account.accountType }}

Is this a shortcoming of angular ternary operators, or an error in my code? Thank you!

Upvotes: 1

Views: 2899

Answers (1)

JLRishe
JLRishe

Reputation: 101652

"" is not the same as null.

I suggest you make use of null, "", etc.'s behavior as "falsy" and do the following:

account.accountType ? "Type: " + account.accountType : ""

or even (thanks to gustavohenke):

account.accountType && "Type: " + account.accountType

If you want to conditionally include HTML in your view, you're probably best off using something like ng-if:

<span ng-if="account.accountType" class=".....">Type: {{ account.accountType }}</span>

Upvotes: 3

Related Questions