angularif-statementangular-template

How can I use "*ngIf else"?


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?


Solution

  • 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.

    Update (Angular 17 and higher)

    Angular now supports control flow syntax (introduced in Angular 17), which allows you to write cleaner and more expressive conditional logic directly in templates. This new syntax enables functionality similar to the ngIf directive but with support for else if.

    Here’s how you can use it:

    @if (a > b) {
      {{a}} is greater than {{b}}
    } @else if (b > a) {
      {{a}} is less than {{b}}
    } @else {
      {{a}} is equal to {{b}}
    }
    

    Benefits:

    This feature is particularly helpful for scenarios where you have multiple conditions to check in your templates, improving both readability and maintainability.