Angular Conditional

Angular Conditional Rendering

Conditional rendering allows you to display or hide sections of your webpage based on component logic.

The primary tool for conditional rendering in Angular is the *ngIf structural directive.

It evaluates a boolean expression and physically adds or removes the element from the Document Object Model (DOM).


The *ngIf Directive

When you attach *ngIf to an HTML tag, Angular evaluates the expression provided.

If the expression evaluates to true, the element is created.

If the expression evaluates to false, the element is completely destroyed, saving browser memory.

*ngIf Example:

<!-- Renders only if showSecretMessage is true -->
<div *ngIf="showSecretMessage" class="alert-box">
  <h4>Secret Information!</h4>
</div>

<!-- Renders if the array length is greater than zero --> <p *ngIf="users.length > 0">We have active users!</p>


Using else with *ngIf

If the condition is false, you often want to display an alternative piece of content (like a login prompt).

Angular allows you to define an else block by referencing an <ng-template> element using a custom template variable.

Template variables are created by prefixing a name with a hashtag #.

*ngIf and else Example:

<!-- If loggedIn is true, show this div. Else, render the 'loggedOut' template. -->
<div *ngIf="loggedIn; else loggedOut">
  Welcome back to your secure dashboard!
</div>

<!-- This block is hidden until summoned by the else condition! --> <ng-template #loggedOut> <p>Please log in to access this page.</p> <button>Login Here</button> </ng-template>


What is <ng-template>?

The <ng-template> tag is a core structural element provided by Angular.

By itself, the content inside an <ng-template> tag is never rendered to the screen.

It acts as a dormant placeholder that only springs to life when a structural directive (like *ngIf) explicitly calls it!

This creates extremely clean and efficient template logic.


Exercise 1 of 2

?

When a *ngIf condition evaluates to false, what happens to the HTML element?

Exercise 2 of 2

?

Which special HTML tag does Angular use to hold an "else" block that remains hidden until explicitly called?