Html Angular 2+ 模板中值的三元运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51842909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:43:56  来源:igfitidea点击:

Ternary operator for values in Angular 2+ template

htmlangulartypescript

提问by Augustin R

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...

我发现这个更好,但是在像*ngIf="A && B". 我们在模板中还有两行代码......

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 getUnitfunction?
Do you have any better idea?

你知道 Angular 2+ 模板是否支持getUnit函数中的三元运算符?
你有什么更好的主意吗?

回答by Krishna Rathore

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

您可以在模板内部使用条件(三元)运算符,如下例所示

 <span> {{selectedSport.key === 'walking' ? 'steps' : 'km'}} </span>

回答by Ramanathan Ganesan

  • 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.
  • 您似乎正在尝试显示所选运动的单位。
  • 最好将逻辑保留在控制器中并将其填充到模型对象中,而视图只显示模型。
  • 淡化视图层的逻辑可能不是更好的设计,也违反了单一职责的规律。