本文转自: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 *ngIf
statement 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.