Angular 2+模板中值的三元运算符 [英] 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>
我发现这种方法更好,但是在诸如*ngIf="A && B"
的多条件情况下使用它可能会比较棘手.而且模板中还有两条代码行...
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...
获取功能
<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.
您是否知道Angular 2+模板是否支持getUnit
函数中的三元运算符?
你有更好的主意吗?
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>
这篇关于Angular 2+模板中值的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!