By Gary simon - Mar 13, 2017
Now that Angular 4 is officially here, I thought it would be worth taking a look at one of the more exciting and usable features: If Else conditionals.
This will make life a bit easier and more structured when dealing with conditionals in the template.
I've recorded a video tutorial that outlines everything below. Be sure to subscribe to the channel for more awesome videos!
With the release of the first stable version of the Angular CLI, it installs an Angular 4 project by default. So, first, run:
> ng -v
If it goes unrecognized, or if the @angular/cli version is not 1.0.0, then you must use npm to install or upgrade the CLI:
> npm install -g @angular/cli
Once it's complete, you can start a new Angular 4 project by running:
> ng new ifelse-proj
> cd ifelse-proj
Then run the following command and open up localhost:4200 in the browser:
> ng serve
In Angular 2, you were unable to specify an else statement after an if. But now with Angular 4, we can!
First, open up /src/app/app.component.ts:
export class AppComponent {
title = 'app works!';
}
Notice within the exported class AppComponent, we have a property that the angular-cli generates automatically called title. We'll use this title property for the basis of our if/else statements going forward.
Let's open up the /src/app/app.component.html file in the same folder and write the following code:
<div *ngIf="title; else login">
The user is logged in.
</div>
<ng-template #login>Please login to continue.</ng-template>
The very first line is saying, "If the title property exists, then show this current div and anything inside of it. Otherwise (else) show the ng-template named #login.
So, if we're to assume the title property is checking a user's logged in state, then this is how you could tackle such a scenario.
You can also use operators. Try changing the *ngIf to:
<div *ngIf="!title; else login">
And then try changing it to:
<div *ngIf="title == 'app works!'; else login">
Simple, huh?
We can also use an if then statement within our Angular 4 templates. Try changing the HTML to the following:
<div *ngIf="title; then logout else login"></div>
<ng-template #login>Please login to continue.</ng-template>
<ng-template #logout>Hi Gary, <button>Logout now</button>.</ng-template>
This way, you can define templates for properties that are true!
If we want to give this some interactivity, change the last line of the HTML example above, to:
<ng-template #logout>Hi Gary, <button (click)="logMeIn()">Logout now</button>.</ng-template>
Then, inside app.component.ts add the logMeIn function:
export class AppComponent {
title:any = true;
logMeIn() {
this.title = false;
}
}
Now, in the browser you can click on the logout now button and it will show the other template.