Issue
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?
Solution
You can use Conditional (ternary) operator, inside of template like below example
<span> {{selectedSport.key === 'walking' ? 'steps' : 'km'}} </span>
Answered By - Krishna Rathore
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.