How can I use "*ngIf else"?
Asked Answered
R

24

1004

I'm using Angular and I want to use *ngIf else (available since version 4) in this example:

<div *ngIf="isValid">
  content here ...
</div>

<div *ngIf="!isValid">
 other content here...
</div>

How can I achieve the same behavior with ngIf else?

Reina answered 24/3, 2017 at 18:18 Comment(0)
R
1477

Angular 4 and 5:

Using else:

<div *ngIf="isValid;else other_content">
    content here ...
</div>

<ng-template #other_content>other content here...</ng-template>

You can also use then else:

<div *ngIf="isValid;then content else other_content">here is ignored</div>
<ng-template #content>content here...</ng-template>
<ng-template #other_content>other content here...</ng-template>

Or then alone:

<div *ngIf="isValid;then content"></div>
<ng-template #content>content here...</ng-template>

Demo:

Plunker

Details:

<ng-template>: is Angular’s own implementation of the <template> tag which is according to MDN:

The HTML <template> element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.

Reina answered 24/3, 2017 at 18:20 Comment(13)
I hoped there was a way just to use <ng-template> without another tag like div, but oddly it is not... I know the <div> gets removed as you use it, but it's kinda weird as implementation I think.Ammeter
@Ammeter You can use <ng-container> for the if-clauseRinarinaldi
Note: you can use ng-container for the container containing *ngIf, but not for the templateAquiline
@Aquiline I figured it out the hard way. But why? why didn't they allow *ngIf to work on ng-template?Jimenez
<div *ngIf="isValid;then content else other_content">here is ignored</div> it is not ignored. it is place fot injecting ng-templatePedigo
Just to add a little info, assigning the template value(#templateValue) directly to component tag and using it with else syntax doesn't work. You should embed the component tag inside of <ng-template> and assign the template value to ng-template like, <ng template #templateValue><your-component-tag></your-component-tag></ng-template>Delfeena
Hi @Bougarfaoui El houcine , Can I use <div #other_content>other content here...</div> instead <ng-template #other_content>other content here...</ng-template> ? Means Can I use div rather than template ?Tevis
I've found that you can create if-then-elseif-elseif-elseif using ng-containers and ng-templates. <ng-container *ngIf="condition1; else ifelse1"></ng-container> <ng-template #ifelse1><ng-contaier *ngIf="condition2; else ifelse2"></ng-container></ng-template> <ng-template #ifelse2><ng-contaier *ngIf="condition2; else ifelse3"></ng-container></ng-template> It's super verbose though, and the need for #ids for each ifelse feels clunky, for something that other web frameworks can accomplish with a single tag/operation.Plerre
Agree with @Josia, it's clunky. If would have been more natural to have an *ngElse much like the *ngSwitchDefault implementation. Because of that, we find it bad practice to use angular's "ngIf..else" construct due to its inconsistency, non intuitiveness and its template variable pollution. It's just weird. You are better off negating the *ngIf for your else blocks, it's more readable most of the time.Gibeon
Having started out on Angular 1 and then left for React, now I am back on a project using Angular 5... is this real life? This construct is legitimately bad.Arrack
This also works in ionic 4 with angular 7. Thanks a lot :)Siegler
Within a 'then' or 'else' statement we're specifying the id of the ng-template tag to use. Isn't that basically a goto-statement?!Rational
Is there a way to bind ngTemplateOutletContext when doing it this way?Osterman
B
267

In Angular 4.x.x

You can use ngIf in four ways to achieve a simple if-else procedure:

  1. Just use If

    <div *ngIf="isValid">
        If isValid is true
    </div>
    
  2. Using If with Else (please notice to templateName)

    <div *ngIf="isValid; else templateName">
        If isValid is true
    </div>
    
    <ng-template #templateName>
        If isValid is false
    </ng-template>
    
  3. Using If with Then (please notice to templateName)

    <div *ngIf="isValid; then templateName">
        Here is never showing
    </div>
    
    <ng-template #templateName>
        If isValid is true
    </ng-template>
    
  4. Using If with Then and Else

    <div *ngIf="isValid; then thenTemplateName else elseTemplateName">
        Here is never showing
    </div>
    
    <ng-template #thenTemplateName>
        If isValid is true
    </ng-template>
    
    <ng-template #elseTemplateName>
        If isValid is false
    </ng-template>
    

Tip: ngIf evaluates the expression and then renders the then or else template in its place when the expression is truthy or falsy respectively.

Typically the:

  • then template is the inline template of ngIf unless bound to a different value.
  • else template is blank unless it is bound.
Boldfaced answered 19/10, 2017 at 15:18 Comment(4)
It seems like the compiler does not accept ...; else .... Probably the ; should be removed.Rriocard
in angular-6, I tested with ...; else ... and it workedCallie
is there a way to do if-elseif-else?Cylindrical
What is the advantage of 4 over 2? Basically both of them has the same result with the difference that in the case of 4 we have an extra <div> without any content.Altocumulus
O
58

For Angular 9/8

Source Link with Examples

    export class AppComponent {
      isDone = true;
    }

1) *ngIf

    <div *ngIf="isDone">
      It's Done!
    </div>

    <!-- Negation operator-->
    <div *ngIf="!isDone">
      It's Not Done!
    </div>

2) *ngIf and Else

    <ng-container *ngIf="isDone; else elseNotDone">
      It's Done!
    </ng-container>

    <ng-template #elseNotDone>
      It's Not Done!
    </ng-template>

3) *ngIf, Then and Else

    <ng-container *ngIf="isDone;  then iAmDone; else iAmNotDone">
    </ng-container>

    <ng-template #iAmDone>
      It's Done!
    </ng-template>

    <ng-template #iAmNotDone>
      It's Not Done!
    </ng-template>
Orientate answered 7/8, 2019 at 15:8 Comment(2)
The question is, which one is better? From a performance point of view, I suspect that the 1st one has 2 directives which need to be evaluated independently, while the other 2 have only one. If you had this in a list/table of thousands of elements, would it not be slower?Anaya
Solution 1 is bad if default value is not truthySelfjustifying
A
49

Just add new updates from Angular 8.

  1. For case if with else, we can use ngIf and ngIfElse.

    <ng-template [ngIf]="condition" [ngIfElse]="elseBlock">
      Content to render when condition is true.
    </ng-template>
    <ng-template #elseBlock>
      Content to render when condition is false.
    </ng-template>
    
  2. For case if with then, we can use ngIf and ngIfThen.

    <ng-template [ngIf]="condition" [ngIfThen]="thenBlock">
      This content is never showing
    </ng-template>
    <ng-template #thenBlock>
      Content to render when condition is true.
    </ng-template>
    
  3. For case if with then and else, we can use ngIf, ngIfThen, and ngIfElse.

    <ng-template [ngIf]="condition" [ngIfThen]="thenBlock" [ngIfElse]="elseBlock">
      This content is never showing
    </ng-template>
    <ng-template #thenBlock>
      Content to render when condition is true.
    </ng-template>
    <ng-template #elseBlock>
      Content to render when condition is false.
    </ng-template>
    
Astilbe answered 22/1, 2020 at 11:3 Comment(4)
Great! We have recently moved to angular 8Primula
1 is not working, i tried the condition to be false but it doesnt display the template elseBlockYesman
@Yesman I think something wrong with your code. If can, u can give me sample of your code.Astilbe
@Yesman please follow the guide from Angular document angular.io/api/common/NgIfAstilbe
T
41

If isShow is true then the first line execute, otherwise secondline executes, because elseBlockShow is working as a reference variable.

<div *ngIf="isShow; else elseBlockShow">
  Text to show for If
</div>
<ng-template #elseBlockShow>
  Text to show for else block
</ng-template>
Toogood answered 23/3, 2021 at 18:21 Comment(0)
N
35

To work with observable, this is what I usually do to display if the observable array consists of data.

<div *ngIf="(observable$ | async) as listOfObject else emptyList">
   <div >
        ....
    </div>
</div>
 <ng-template #emptyList>
   <div >
        ...
    </div>
</ng-template>
Nata answered 29/9, 2017 at 9:3 Comment(0)
C
25

Here's some nice and clean syntax on Angular's NgIf and using the else statement. In short, you will declare an ElementRef on an element and then reference it in the else block:

<div *ngIf="isLoggedIn; else loggedOut">
   Welcome back, friend.
</div>

<ng-template #loggedOut>
  Please friend, login.
</ng-template>

I've taken this example from NgIf, Else, Then which I found to be really well explained.

It also demonstrates using the <ng-template> syntax:

<ng-template [ngIf]="isLoggedIn" [ngIfElse]="loggedOut">
  <div>
    Welcome back, friend.
  </div>
</ng-template>

<ng-template #loggedOut>
  <div>
    Please friend, login.
  </div>
</ng-template>

And also using <ng-container> if that's what you're after:

<ng-container
  *ngIf="isLoggedIn; then loggedIn; else loggedOut">
</ng-container>

<ng-template #loggedIn>
  <div>
    Welcome back, friend.
  </div>
</ng-template>
<ng-template #loggedOut>
  <div>
    Please friend, login.
  </div>
</ng-template>

Source is taken from here on Angular's NgIf and Else syntax.

Clairvoyant answered 14/2, 2021 at 12:39 Comment(2)
I don't find using template for just a single line nice and cleanForswear
@Forswear same, it is just the example given for both syntaxes. *ngIf is the way to go unless needed.Clairvoyant
J
14

You can use <ng-container> and <ng-template> to achieve this:

<ng-container *ngIf="isValid; then template1 else template2"></ng-container>

<ng-template #template1>
     <div>Template 1 contains</div>
</ng-template>

<ng-template #template2>
     <div>Template 2 contains </div>
</ng-template>

You can find the StackBlitz Live demo below:

Live demo

Jonme answered 24/10, 2019 at 11:43 Comment(0)
B
9

"bindEmail" will check if email is available or not. If email does exist then Logout will show. Otherwise Login will show.

<li *ngIf="bindEmail;then logout else login"></li>
<ng-template #logout><li><a routerLink="/logout">Logout</a></li></ng-template>
<ng-template #login><li><a routerLink="/login">Login</a></li></ng-template>
Benzoate answered 23/7, 2017 at 13:13 Comment(1)
This doesn't work. If it were correct, then it still wouldn't add any value because the accepted answer shows already how to do it.Muttonchops
P
9
<div *ngIf="isValid; else templateName">
  If isValid is true
</div>

<ng-template #templateName>
  If isValid is false
</ng-template>
Proxy answered 14/3, 2023 at 11:13 Comment(1)
Same as https://mcmap.net/q/53209/-how-can-i-use-quot-ngif-else-quot/…Santasantacruz
S
8

Since Angular 17, you can use built-in control flow, an alternative template syntax for conditionally showing, hiding or repeating elements. It allows you to do if else like the following:

@if (isValid) {
  content here ...
} @else {
  other content here...
}

With this syntax, it's not necessary to use ng-template for the else case. Additionally, it allows @else if, which has not been possible before.

As of Angular 17, control flow is in developer preview and may change before becoming stable.

Seafowl answered 5/12, 2023 at 7:29 Comment(0)
M
7

You can also use the JavaScript short ternary conditional operator ? in Angular like this:

{{doThis() ? 'foo' : 'bar'}}

or

<div [ngClass]="doThis() ? 'foo' : 'bar'">
Monophyletic answered 13/5, 2019 at 7:58 Comment(0)
S
6

An ngif expression resulting value won’t just be the Boolean true or false.

If the expression is just an object, it still evaluates it as truthiness.

If the object is undefined, or non-existent, then ngif will evaluate it as falseness.

Common use is if an object loaded, exist, and then display the content of this object, otherwise display "loading.......".

 <div *ngIf="!object">
     Still loading...........
 </div>

<div *ngIf="object">
     <!-- the content of this object -->

           object.info, object.id, object.name ... etc.
 </div>

Another example:

  things = {
 car: 'Honda',
 shoes: 'Nike',
 shirt: 'Tom Ford',
 watch: 'Timex'
 };

 <div *ngIf="things.car; else noCar">
  Nice car!
 </div>

<ng-template #noCar>
   Call a Uber.
</ng-template>

 <!-- Nice car ! -->

Another example:

<div *ngIf="things.car; let car">
   Nice {{ car }}!
 </div>
<!-- Nice Honda! -->

ngif template

ngif Angular 4

Schulze answered 11/1, 2018 at 18:0 Comment(0)
D
6

There are two possibilities to use an if condition on an HTML tag or templates:

  1. *ngIf directive from CommonModule, on HTML tag;
  2. if-else

Enter image description here

Desquamate answered 13/11, 2018 at 16:30 Comment(0)
C
6

**ngIf else**

<div *ngIf="isConditionTrue;else other_condition">
    your content here
</div>

<ng-template #other_condition>other content here...</ng-template>

**ngIf then else**

<div *ngIf="isConditionTrue;then content else other_content">here is ignored</div>
<ng-template #content>content here...</ng-template>
<ng-template #other_content>other content here...</ng-template>


**ngIf then**

<div *ngIf="isConditionTrue;then content"></div>
<ng-template #content>content here...</ng-template>
Conformist answered 1/6, 2022 at 9:28 Comment(0)
G
5

Syntax for ngIf/Else

<div *ngIf=”condition; else elseBlock”>Truthy condition</div>
<ng-template #elseBlock>Falsy condition</ng-template>

Enter image description here

Using NgIf / Else/ Then explicit syntax

To add a then template, we just have to bind it to a template explicitly.

<div *ngIf=”condition; then thenBlock else elseBlock”> ... </div>
<ng-template #thenBlock>Then template</ng-template>
<ng-template #elseBlock>Else template</ng-template>

Enter image description here

Observables with NgIf and Async Pipe

For more details

Enter image description here

Goldfilled answered 11/10, 2018 at 8:10 Comment(0)
M
5

ng-template

<ng-template [ngIf]="condition1" [ngIfElse]="template2">
        ...
</ng-template>


<ng-template #template2> 
        ...
</ng-template>
Meshwork answered 18/5, 2019 at 9:3 Comment(0)
S
4

In Angular 4.0 if..else syntax is quite similar to conditional operators in Java.

In Java you use to "condition?stmnt1:stmnt2".

In Angular 4.0 you use *ngIf="condition;then stmnt1 else stmnt2".

Shewchuk answered 11/4, 2017 at 3:51 Comment(3)
looks like Oracle case when expression.. :-)Chaeta
You're referring to the ternary operator which exists in most C-based languages but this is closer to Kotlin's if expressions.Caspian
condition?stmnt1:stmnt2, this doesn't work only in java. So it is not only java relatedTwosided
T
4
<div *ngIf="show; else elseBlock">Text to show</div>
<ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
Tights answered 6/7, 2020 at 5:31 Comment(1)
An explanation would be in order. E.g., what is the idea/gist? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).Dillon
L
3

In Angular 4, 5 and 6

We can simply create a template reference variable 2 and link that to the else condition inside an *ngIf directive

The possible syntaxes 1 are:

<!-- Only If condition -->
<div *ngIf="condition">...</div>
<!-- or -->
<ng-template [ngIf]="condition"><div>...</div></ng-template>


<!-- If and else conditions -->
<div *ngIf="condition; else elseBlock">...</div>
<!-- or -->
<ng-template #elseBlock>...</ng-template>

<!-- If-then-else -->
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>...</ng-template>
<ng-template #elseBlock>...</ng-template>


<!-- If and else conditions (storing condition value locally) -->
<div *ngIf="condition as value; else elseBlock">{{value}}</div>
<ng-template #elseBlock>...</ng-template>

DEMO: https://stackblitz.com/edit/angular-feumnt?embed=1&file=src/app/app.component.html

Sources:

  1. NgIf - directive
  2. Template syntax
Lightheaded answered 8/8, 2018 at 20:24 Comment(1)
Your answer states it's valid for Angular 4 through 6. It made sense 2018 when you wrote it but now, 4 years later, it suggests that it's not necessarily valid for the latest version. I just used it in Angular 13 and it works perfectly. You may want to consider updating the formulation to make your answer from great to even better.Echinate
T
2
<div *ngIf="this.model.SerialNumber != '';then ConnectedContent else DisconnectedContent" class="data-font">    </div>

<ng-template #ConnectedContent class="data-font">Connected</ng-template>
<ng-template #DisconnectedContent class="data-font">Disconnected</ng-template>
Tso answered 17/4, 2018 at 15:44 Comment(1)
An explanation would be in order. E.g., what is the idea/gist? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).Dillon
D
1

So, this isn't actually using ng-if but many of the suggestions appear to deal with writing text in a conditional statement. I think this way is the best way to do that with least code or complication. You be the judge.

<div>{{variable == null ? 'Testing1' : 'Testing2'}}<div>
OR
<div>{{variable == null ? var1 : var2 }}<div>
Duplicity answered 2/11, 2022 at 17:47 Comment(0)
B
1

The long waiting feature to support the if, else-if, else has been supported in Angular 17.

you can do it by following the below syntax:

`@if() {
   <div>Inside if condtion</div>
} @else if() {
   <div>Inside if else condtion</div>
} @else {
   <div>Inside else</div>
}`
Brumaire answered 18/3 at 9:14 Comment(0)
S
0

The way I went about with is to have two flags in the component and two ngIfs for the corresponding two flags.

It was simple and worked well with material as ng-template and material were not working well together.

Sightread answered 20/9, 2018 at 7:29 Comment(1)
Can you provide one or more code examples? (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.)Dillon

© 2022 - 2024 — McMap. All rights reserved.