Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

How to use *ngIf else in Angular?

Get support on Angular & Typescript related technology.
Post Reply
admin
Site Admin
Posts: 45

How to use *ngIf else in Angular?

Post by admin » Mon Oct 14, 2019 5:40 pm

You can use ngIf in four way to achieve simple if else procedure:

Just Use If

Code: Select all

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

Code: Select all

<div *ngIf="isValid; else templateName">
    If isValid is true
</div>

<ng-template #templateName>
    If isValid is false
</ng-template>
Using If with Then (Please notice to templateName)

Code: Select all

<div *ngIf="isValid; then templateName">
    Here is never showing
</div>

<ng-template #templateName>
    If isValid is true
</ng-template>
Using If with Then and Else

Code: Select all

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

Post Reply