AngularT2 Dark_1200x303

A quick tutorial on how to use the *ngIf else directive in Angular to perform comparisons in your Angular apps.

What is Angular?

This post aims to solve common questions about using *ngIf while developing web apps with Angular. For those new to it, Angular, Google's JavaScript (TypeScript) framework for building web applications, mobile or desktop, has over 56,000 stars on GitHub. It's maintained by the Angular team at Google and a host of community members and organizations.

Before You Start

To be able to follow through in this article's demonstration you should have:

  • A integrated development environment like VS Code
  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (usually ships with Node installation)
  • Angular CLI version 9.0
  • The latest version of Angular (version 9)
    // run the command in a terminal
        ng version

Confirm that you are using version 9, and update if you are not.

  • Download this tutorial's starter project here to follow through the demonstrations
  • Unzip the project and initialize the node modules in your terminal with this command: npm install

Other nice-to-haves are:

  • A working knowledge of the Angular framework at a beginner level

Comparisons in Programming Logic

When building your Angular application or any other application, there is always a time when you have to compare between two entities. These entities can be variables or array items. The concept of comparison has helped break down a lot of complex logic into simple terms. These comparisons can be done with conditionals.

Conditionals in Angular 9

For every comparison, there is a condition — like, if today is Friday, then display "Happy Friday!"

Just like most programming languages, Angular has directives like if, for and switch for handling comparisons. In this post, you will learn how to use the if directive to handle comparisons in Angular.

The ngIf Directive + else

According to the Angular API, the ngIf directive is a structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. When the expression evaluates to true, Angular renders the template provided in a then clause, and when false or null, Angular renders the template provided in an optional else clause.

ngIf Syntax

The ngIf directive syntax looks like this:

<div *ngIf="condition">Content to render when condition is true.</div>

An extended version of this would look like this:

<ng-template [ngIf]="condition">
  <div>Content to render when condition is true.</div>
</ng-template>

Finally, you can add an outcome for when your conditions were not met. This is where the else clause comes into an if statement. The idea is that your logic should be constructed like this: If condition is met, do this, else do something new. Adding the else clause, the syntax looks like this:

<div *ngIf="condition; else elseBlock">
  Content to render when condition is true.
</div>
<ng-template #elseBlock>
  Content to render when condition is false.
</ng-template>

Demo

Let's build a simple toggle Angular component to illustrate the ngIf directive. Open up your ng canvas project you already unzipped in VS Code, and inside your src directory you will find an app folder. The app.component.ts file should look like this:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ngcanvas';
}

To start off, we will generate a new component to work with. Open the terminal inside VS Code and run the command below inside it:

ng generate component comparisons

You should have a new comparisons folder inside the app directory. Clean up your app.component.html file and paste this code block inside it:

<div style="text-align:center">
  <h1>
    Welcome to ngIf app
  </h1>
</div>
<h2> <app-comparisons></app-comparisons></h2>

For the toggle logic, open your comparisons.component.html file and replace the paragraph code (comparisons work!) with this code block below:

<h1>
  <button (click)="toggleOn =!toggleOn">Toggle Greetings</button>
</h1>
<div *ngIf="!toggleOn">
<h2>Hello</h2>
<p>Good morning to you</p>
</div>
<hr>
<p>Today is Friday and this is a dummy text element to make you feel better</p>
<p>Understanding the ngIf directive with the else clause</p>

Here, we first created a button and assigned it to a toggleOn event which turns either true or false as you click.

Then, we have a div tag that contains the greetings. On the div tag we added the ngIf directive that would be displayed if the value of toggleOn is false. After that, we added some dummy paragraphs.

the toggle app

This is how to use the ngIf directive. It can be used in all types of use cases and comparisons you can think of in your component template.

The else Clause

There are some scenarios where you want to display or return something else if the condition you set does not work out.

Like heading to the store to get Snickers but they are out of stock, so you get Bounty instead.

Angular provides an additional enhancement to the ngIf directive by adding an else clause. This also has a very simple logic: If the condition you specified is not fulfilled, do this instead.

In our demo above, you see that if the toggleOn value is false, nothing is displayed; but if it is on, then the greetings will be displayed. With the else clause, we can now display something when the toggleOn value is false. Modify your your comparisons.component.html file with this newer version below:

<h1>
  <button (click)="toggleOn =!toggleOn">Toggle Greetings</button>
</h1>
<div *ngIf="!toggleOn; else elseBlock">
<h2>Hello</h2>
<p>Good morning to you</p>
</div>
<ng-template #elseBlock>No greeting, Lagbaja nothing for you.</ng-template>
<hr>
<p>Today is Friday and this is a dummy text element to make you feel better</p>
<p>Understanding the ngIf directive with the else clause</p>

Now the app shows the predefined content for the else side of things when you make your comparisons.

Other Perks

The ngIf directive also has some more perks you might want to know about, one of which is local variable assignment. Sometimes, the result of the ngIf directive is not a boolean. Angular allows you to save variables locally and access them with your ngIf directive.

Using the snacks analogy I introduced during the else section, open your comparisons.component.ts file and replace the content with the code block below:

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-comparisons',
  templateUrl: './comparisons.component.html',
  styleUrls: ['./comparisons.component.css']
})
export class ComparisonsComponent implements OnInit {
  Snacks = {
    chocolate: 'Snickers'
  };
constructor() { }
ngOnInit() {}
}

Now we have declared a snacks object and saved Snickers as the only type of chocolate in it. Update your comparisons.component.html file with the code block below:

<h1>
  <button (click)="toggleOn =!toggleOn">Toggle Greetings</button>
</h1>
<div *ngIf="!toggleOn; else elseBlock">
<h2>Hello</h2>
<p>Good morning to you</p>
</div>
<ng-template #elseBlock>No greeting, Lagbaja nothing for you.</ng-template>
<hr>
<p>Today is Friday and this is a dummy text element to make you feel better</p>
<p>Understanding the ngIf directive with the else clause</p>
<div *ngIf="!Snacks.chocolate; else noSnickers; let chocolate">
  Nice {{ chocolate }}!
</div>
<ng-template #noSnickers>
  Get bounty instead.
</ng-template>

If you serve the application, you will see that you can indeed access Snickers from your directive and even the else block in it. The applications of these ngIf directive concepts are endless and are only limited to your creativity and the use cases you can imagine.

Conclusion

You have gone through the Angular ngIf directive and how it is used to make handling comparisons easy. You were also introduced to additional concepts provided by the directive, like the else clause and the local variable assignment, and how you can start using them in your apps today. Happy coding!


5E9A474B-EBDB-439E-8A4A-3B041B0BEDA6
About the Author

Nwose Lotanna Victor

Nwose Lotanna Victor is a web technology enthusiast who documents his learning process with technical articles and tutorials. He is a freelance frontend web developer based in Lagos, Nigeria. Passionate about inclusion, community-building and movies in Africa, he enjoys learning new things and traveling.

Related Posts

Comments

Comments are disabled in preview mode.