Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 994
Augustin R Avatar asked Aug 14 '18 13:08

Augustin R


3 Answers

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

 <span> {{selectedSport.key === 'walking' ? 'steps' : 'km'}} </span>
like image 167
Krishna Rathore Avatar answered Oct 21 '22 12:10

Krishna Rathore


  • 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.
like image 2
Ramanathan Ganesan Avatar answered Oct 21 '22 11:10

Ramanathan Ganesan


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>
like image 1
Tauseef Arshad Avatar answered Oct 21 '22 11:10

Tauseef Arshad