Ternary operator for values in Angular 2+ template

I have in my template something like this:

<span *ngIf="selectedSport.key === 'walking'"> steps </span> <span *ngIf="selectedSport.key !== 'walking'"> km </span> 

I found this spelling quite ugly, and two lines for this... Meh. So I tried to look for alternatives to this.

NgIfElse

<span *ngIf="selectedSport.key === 'walking'; else elseSpan"> steps </span> <ng-template #elseSpan> km </ng-template> 

I found this one better, however it may be tricky to use in case of multi-condition like *ngIf="A && B". And we still have two code lines in template...

get function

<span> {{getUnit(selectedSport.key)}} </span> 
getUnit(sportKey: string): string { return sportKey === 'walking' ? 'steps' : 'km'; } 

This is quite better as template gets more readable. However I would like not to add a function in my component for this.

Do you know if Angular 2+ templates support ternary operators as in the getUnit function?
Do you have any better idea?

1

3 Answers

You can use Conditional (ternary) operator, inside of template like below example

 <span> {{selectedSport.key === 'walking' ? 'steps' : 'km'}} </span> 
2
  • It seems that you are trying to display unit of selected sport.
  • It is better to keep the logic in controller and populate it in model object and view just display the model.
  • Diluting the logic in view layer may not a better design and violates law of single responsibility.

if you want multiple ternary operator you can use like that

 <span >{{this.commentsType === itemType.All ? counter.allCounts : this.commentsType === itemType.Project ? counter.projectCount : this.commentsType === itemType.Customer ? counter.customerCommunication : 0}}</span> 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like