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

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

问题描述

考虑以下代码示例:

<!-- 标记在这里-->

<ng-template #elseBlock><div><!-- 此处附加标记-->

</ng-模板>

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

<!-- 标记在这里-->

<div *ngIf="!condition"><!-- 此处附加标记-->

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

解决方案

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

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

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

那些投票结束这个问题的意见是被误导的.人们对某事可能有不同意见,并不意味着没有值得提出的有效观点.

如果使用 else 只是一个偏好问题,我怀疑 Angular 开发人员会像他们一样优先考虑 Angular 4.

正如@Ishnark 指出的那样,这也可能会对性能产生影响.

Consider the following code sample:

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

解决方案

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.

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

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.

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

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

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

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆