45

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?

Augustin R
  • 7,089
  • 3
  • 26
  • 54

3 Answers3

108

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

 <span> {{selectedSport.key === 'walking' ? 'steps' : 'km'}} </span>
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Krishna Rathore
  • 9,389
  • 5
  • 24
  • 48
  • Thanks, @narendra-jadhav for improving my answer. – Krishna Rathore Aug 12 '19 at 09:31
  • 2
    Just to expand on this with regards to an observable value, you must wrap the observable and async pipe in parentheses like {{ (someObs$ | async) === 'someValue' ? 'output if true' : 'output if false' }} – Jacob Roberts Sep 29 '20 at 12:59
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.
1

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>
Tauseef Arshad
  • 583
  • 5
  • 13