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
Welcome back, user!
Please log in to continue.
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
<ng-template #loadingOrError>
Loading or Authentication failed...
Note: <ng-template> itself is never rendered; it is a way to group content that Angular uses programmatically.