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?
You can use Conditional (ternary) operator, inside of template like below example
<span> {{selectedSport.key === 'walking' ? 'steps' : 'km'}} </span>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With