[转]Angular 4 *ngIf/Else

本文转自:http://tylerscode.com/2017/03/angular-4-ngifelse/

As you may know it wasn’t that many months ago that Angular 2 left RC and went Full Release(back in August). We are already upon the next big release of Angular with v4. Angular 4.0.0-rc.1 was released in late February with rc.2 hot on it’s heels 6 days later, today, March 2nd. There are lots of improvements including smaller bundle sizes and faster compilation. My favorite new feature at the moment is the new NgIf/Else syntax.

Previously, you may have used something like this:

1
2
3
4
5
6
7
< div * ngIf = "someCondition" >
   < h1 >Condition Passed!</ h1 >
</ div >
 
< div * ngIf = "!someCondition" >
   < h1 >Condition Failed!</ h1 >
</ div >

Now you can use syntax like this:

1
2
3
4
5
6
7
< div * ngIf = "someCondition; else falsyTemplate" >
   < h1 >Condition Passed!</ h1 >
</ div >
 
< ng-template #falsyTemplate>
   < h1 >Condition Failed!</ h1 >
</ ng-template >

You can specify another template using ng-template, give it a variable using # and then reference it in the *ngIf statement with an else clause.

You can also use a more explicit syntax with NgIf/Else/Then. It would look something like this:

1
2
3
4
5
6
7
8
9
< div * ngIf = "someCondition; then truthyTemplate else falsyTemplate" ></ div >
 
< ng-template #truthyTemplate >
   < h1 >Condition Passed!</ h1 >
</ ng-template >
 
< ng-template #falsyTemplate>
   < h1 >Condition Failed!</ h1 >
</ ng-template >

In my opinion this helps code readability as it makes it more explicit and easier to follow. No more falsy checks with !someCondition like code.

Also, the async pipe was added to *ngIf. Previously you may have had a form or page that contained several fields that all independently subscribed to observables using the async pipe. It may have looked something like this:

1
2
3
< p >{{someObservableOne | async}}</ p >
< p >{{someObservableTwo | async}}</ p >
< p >{{someObservableThree | async}}</ p >

Now you can wrap all those observables into a single observable and subscribe to it in the *ngIfstatement and assign a local object variable to reference in all your fields like this:

1
2
3
4
5
6
7
< div * ngIf = "someObservable | async; else loadingScreen; let myObject" >
   < p >{{myObject.propertyOne}}</ p >
   < p >{{myObject.propertyTwo}}</ p >
   < p >{{myObject.propertyThree}}</ p >
</ div >
 
< ng-template #loadingScreen>loading...</ ng-template >

This code, in my opinion, is cleaner because it only subscribes to a single observable once to retrieve data. I hope this feature is as beneficial to others as it is to me.

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值