Angular 7 NgIf, Else, Then – Work Like a Pro

Article By Rawat Digamber on

Angular 7 Ngif Else is the not-so-simple version of conditional if else in Angular. Angular 7 ngif else allows you to switch between content from a conditional expression. As we have already mentioned, it is not as simple as you would assume. Angular ngif else is a far better version of regular if else since it comes with many helpful syntaxes. Asynchronous objects also make Angular ngif else look better.

Let’s take a closer look at Angular ngif else and learn how we can make better use of this in Angular apps.

Decoding Angular NgIf

To begin with, Angular 7 Ngif works like regular if else only. It will evaluate the expression and it will show or hide the element based on the result of that evaluation. Next up, Angular will simply remove or add the DOM nodes. Or it will remount or mount the components. It will be in tandem with the change in expression if that’s a possibility.

You need to know that Ngif basic syntax is effective and simple. Here you need to prefix an asterisk (*) with the directive name. Then you can include it inside the template, wherever you wish to have it.

Well, we are definitely going to address why use an asterisk as we explore ngIf in Angular 7.

Using ngIf is not difficult in Angular 7, it’s pretty easy and straightforward. You just have to add asterix (*) symbol along with ngIf syntax.

// Directive formula

* + ngIf = *ngIf

Include this *ngIf directive within your Angular template.

We’ll provide details why we use the asterisk syntax, soon.

Learn to Use Angular Ngif

As far as using *ngIf is concerned, there are 4 main ways. We will start with the basic form first below:

@Component({
  selector: 'my-app',
  template: `
    <div *ngIf="userLoggedIn">
      Hello <strong>User</strong>
    </div>
  `,
})

export class AppComponent  {
  userLoggedIn = true;
}

We can go for expressions similar to JavaScript to get a final value to pass on to *ngIf. We can also take the help of various operators and multiple variables to make it easier for us.

Using Various Logical operators with NgIf in Angular 7

Following are the methods through which we can play with *ngIf in Angular 7:

Using Logical NOT (!) Operator with NgIf in Angular

@Component({
  selector: 'my-app',
  template: `
    <div *ngIf="!userLoggedIn">
      Login, <strong>user</strong>
    </div>
  `,
})

export class AppComponent  {
  userLoggedIn = false;
}

Using Logical AND (&&) Operator with Angular NgIf

Check out the && operator example in Angular with *ngIf.

@Component({
  selector: 'my-app',
  template: `
    <input type="checkbox" [(ngModel)]="checked"/>
    <input type="checkbox" [(ngModel)]="checked2" />

    <span *ngIf="checked && checked2">
      Show this text when both checkboxes are checked!
    </span>
  `,
})

export class AppComponent  {
  alert('Check both the checkboxes to show message')
}

Using Logical OR (||) Operator with Angular NgIf

Check out the || operator example in Angular with *ngIf.

@Component({
  selector: 'my-app',
  template: `
  <div *ngIf="x == 5 || y == 5">
    Angular Logical || Testing
  </div>
  `,
})

export class AppComponent {
  x = 5;
  y = 9;
}

We have presented a couple of examples for your reference. We hope that you understood the various ways to implement *ngIf.

Let’s examine some exciting examples below.

Exploring *ngIf and Else in Angular 7

Let’s explore *ngIf else in Angular 7 next.

Else statement is an excellent addition to Angular 7. It has its roots in Angular JS. There is nothing complicated about this though. If this, execute this else execute something else. It’s as simple as it gets. In Angular JS it used to mess with the template as you had to negate the expression in order to have else part. Or we had to use directives like ng-hide and ng-show to get the same done.

We don’t have to navigate through any such complication any more thanks to Angular if else directive.

Let’s take a look at how we can explore the else statement inside the template of a component to make sure that render flow is in control.

@Component({
  selector: 'my-app',
  template: `
    <div *ngIf="userLoggedIn; else userloggedOut">
      Hello User
    </div>

    <ng-template #userloggedOut>
      Hello User, Login
    </ng-template>
  `,
})

export class AppComponent {
  userLoggedIn = false;
  userloggedOut = true;
}

The good thing about this setup is that you can utilize this to unmount or mount components based on conditions.

There are 2 things to keep in mind here. First and foremost, #userloggedOut, the template source variable. You can choose whichever name you find appealing here. Next up we will address <ng-template>. You might be familiar with <template>, the equivalent of it in HTML5. Moreover, it is regarded as a virtual.

In fact, <template> has inspired <ng-template>. It was part of the Angular V2-V4. Moreover, right now it has been deprecated thanks to <ng-template>.

We have already mentioned that it is regarded as virtual. As a result, the contents will cease to exist until you need it in the compiled DOM. It is going to depend on the outcome of the evaluation of the ngif else expression. Angular will use the content when it is needed and replace it.

Well, it is as simple as it gets. We are talking about a virtual container here. It will not render any contents without being ready.

Well, before we explore the rest, we have to address the asterisk * business which we had promised earlier on.

Taking a Closer Look at Angular Ngif Else and Ng-template

Okay, here we need to address Angular If sugar syntax. Let’s take a look:

<div *ngIf="userLoggedIn">
  Hello User
</div>

As per our latest findings, we can say for sure that it is equivalent to this:

@Component({
  selector: 'my-app',
  template: `
    <ng-template [ngIf]="userLoggedIn">
      <div>
        Hello User.
      </div>
    </ng-template>
  `,
})

export class AppComponent {
  userLoggedIn = true;
}

Angular will be responsible for converting *ngif syntax to what we just saw, across the system. Moreover, we both know that it is not the fastest solution. However, it will tell you more about how [ngIf] comes into play. Here we are exposed to the property binding syntax here.

Moreover, yes, it indicates that we will be able to deliver ngIfThen, ngIfElse and *ngIf in the same manner:

<ng-template [ngIf]="userLoggedIn" [ngIfElse]="userloggedOut">
    Hello User
</ng-template>

<ng-template #userloggedOut>
    User Login
</ng-template>

Well, there is no need for us to jump ahead in this fashion. We are yet to cover ngIfThen.

Covering *ngIf, Then and Else

Here we are moving *ngIf template outside. That’s all it means. What is the significance of this? Well, it offers increased flexibility in certain use cases. We will be able to alter the reference to the template to then dynamically. Alternatively, in other words, we will be swapping <ng-template> as and when required. However, one must keep in mind that it is a less frequent use.

The best thing about this approach is that you will be able to come up with more descriptive if/then/else segment. Here we explore preferences and cases as stated already.

@Component({
  selector: 'my-app',
  template: `
    <ng-container
      *ngIf="isLoggedIn; then userloggedIn; else userloggedOut">
    </ng-container>

    <ng-template #userloggedIn>
      <div>
        Hello User
      </div>
    </ng-template>

    <ng-template #userloggedOut>
      <div>
        Please Login
      </div>
    </ng-template>
  `,
})

export class AppComponent {
  userloggedIn = true;
}

Here the thinking in the flow of statements has been accustomed to the syntax. It aligns well with our thoughts, like this:

ngIf = condition ? then : else;

Opting for ng-container is an option in this case. Well, we are making sure that DOM node is not rendered until the template has been rendered.
Moreover, when it comes to using the then block, the content enclosed in the opening and closing tags will be ignored. We have elaborated the same in the above example involving <ng-container>.

Feel free to contact me, If you are looking for a freelance web and mobile app developer in India, with the following skills: Angular JS, Angular 2+, Node JS, Firebase, MongoDB, Ionic Framework and WordPress.

I also offer remote contracting services to clients across the globe.

Get Started