Writing If, Else Statements using NgIf

Writing If, Else statements are the fundamental elements of programming. Starting from version 4, Angular supports writing “If” as well as “Else” statements. Before that only “If” statements were allowed in Angular. These statements are defined within the “ngIf” directive.

Defining ngIf and writing If, Else Statements

As writing if else statements in your Angular is one of the most basic task that you will frequently have to use, understanding this control flow is very important for Angular developers.

We can define the “ngIf” inside of an HTML element similar to writing “For Loops“.

Writing If, Else Statements Using NgIf

Writing If, Else Statements Using NgIf

Inside of the quotes, we bind the “ngIf” statement to a template expression. We can add “else” as well as “then” statements to define extra local template variable. The “if” statement should always in returns  true or false value.

Demo using ngIf

To get started with writing if else statements using ngIf in your angular app, add the following boolean value inside your app.component.ts file:

iAmTrue: boolean = true;
The syntax is a basic declaration of TypeScript boolean type. Next, we will make use of this boolean value to use if else statements.

In your templateUrl HTML file, write the following code:

<div *ngIf="iAmTrue; then trueTempl else falseTempl">

This text will be hidden.

</div>

<ng-template #trueTempl>I'm true.</ng-template>

<ng-template #falseTempl>I'm false.</ng-template>
Save both files and browse the change in the browser. You should be able to see the following change reflected:
Demo using ngIf

Demo using ngIf

Since the value of property “iAmTrue” is true, the control flow switches over to showing “trueTempl“. If this value was false, the “falseTempl” would have rendered on the view. Also, note that the text declared inside the if else then statement i.e. “This text will be hidden.” was not displayed at all.

This was a simple demo of writing if else statements. We can create complex, dynamic views with the help of this ngIf declarative and templates in the same manner.

  • Leave a Reply