ngIf-else vs两个ngIf条件 [英] ngIf - else vs two ngIf conditions

查看:1238
本文介绍了ngIf-else vs两个ngIf条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码示例:

<div *ngIf="condition; else elseBlock">
    <!-- markup here --> 
</div>
<ng-template #elseBlock>
     <div>
         <!-- additional markup here -->
     </div> 
</ng-template>

我可以实现相同功能的另一种方法是:

Another way I can achieve the same functionality is:

<div *ngIf="condition">
    <!-- markup here --> 
</div>
<div *ngIf="!condition">
     <!-- additional markup here -->
</div>

我想知道应该使用这两种方式中的哪一种的具体原因以及为什么?

I want to know specific reasons for which of these two ways should be used and why?

推荐答案

使用else可以避免两次编写条件,这可能是bug的来源,因此我会优先使用它.如果愿意,还可以将else模板放在模板的底部,这样可以使模板更易于阅读.

Using else lets you avoid writing the condition twice, which could be a source of bugs, so I would use that preferentially. You can also put the else template down at the bottom of your template if you so choose, which can make the template easier to read.

如果要使用async管道解开可观察对象,则编写起来会容易得多

If you are unwrapping an observable with the async pipe, then it is much easier to write

<div *ngIf="myItems$ | async as myItems; else noItemsYet">

而不是添加另一个<div *ngIf="!(myitems | async)">,这也将迫使Angular创建另一个内部订阅.

than to add another <div *ngIf="!(myitems | async)">, which would also force Angular to create another internal subscription.

以投票方式结束这个问题的观点被误导了.人们对某些事情可能有不同的看法,这并不意味着没有值得提出的有效观点.

Those voting to close this question as a matter of opinion are misguided. The fact that people might have different opinions on something does not mean that there are not valid points that are worth putting forward.

如果仅使用else是一个优先事项,我怀疑Angular开发人员是否会像他们一样优先使用Angular 4.

If using else was a matter of mere preference, I doubt the Angular developers would have prioritized it for Angular 4 as they did.

正如@Ishnark指出的那样,可能还会影响性能.

As @Ishnark points out, there may be performance implications as well.

这篇关于ngIf-else vs两个ngIf条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆