Back to course

Built-in Structural Directives: *NgIf

The Complete Angular Developer: From Zero to Hero

15. Built-in Structural Directives: *NgIf

Structural directives are responsible for shaping or reshaping the DOM structure, usually by adding, removing, or manipulating elements. They are always prefixed with an asterisk (*).

The *NgIf Directive

*NgIf conditionally adds or removes an element and its subtree from the DOM based on a boolean expression.

Important: *NgIf doesn't just hide the element (like CSS display: none); it physically removes the element from the DOM, saving resources and potentially preventing errors.

Simple Conditional Rendering

Component Class:

typescript export class AuthComponent { isLoggedIn: boolean = false; }

Template:

html <button (click)="isLoggedIn = !isLoggedIn"> Toggle Login Status </button>

<!-- Only render the welcome message if isLoggedIn is true --> <div *ngIf="isLoggedIn"> <h2>Welcome back, user!</h2> </div> <!-- Only render the login prompt if isLoggedIn is false --> <div *ngIf="!isLoggedIn"> <p>Please log in to continue.</p> </div>

Using *NgIf with else (Ng-Template)

Angular provides a mechanism to specify an alternative template when the primary condition is false using the else keyword and the <ng-template> element.

html

<div *ngIf="isLoggedIn; else loadingOrError"> Content Loaded Successfully. </div> <!-- ng-template is rendered ONLY if isLoggedIn is false -->

<ng-template #loadingOrError>

<p>Loading or Authentication failed...</p> </ng-template>

Note: <ng-template> itself is never rendered; it is a way to group content that Angular uses programmatically.