您的位置:首页 > Web前端 > AngularJS

[转]Angular 4 *ngIf/Else

2018-10-09 16:41 405 查看

本文转自: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:

Now you can use syntax like this:

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:

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:

Now you can wrap all those observables into a single observable and subscribe to it in the 

*ngIf
statement and assign a local object variable to reference in all your fields like this:

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.

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: