liveBook · Manning

ngIf

As explained in Modern Angular

NgIf is an Angular structural directive that conditionally includes a template based on an expression.

ngIf is an Angular structural directive that adds or removes part of the DOM according to a template expression. It commonly gates validation messages and other conditional UI. section 10.1.1

Standalone components can import NgIf directly. Angular v15 made CommonModule entities standalone, avoiding the broader CommonModule import when a component needs only this directive. section 2.3.1

Login validation message

A standalone login component can display a warning while either credential is empty: <span class="warning" *ngIf="!credentials.email || !credentials.password">Please fill in all the required fields</span>. Its component metadata imports both FormsModule and NgIf.

Use ngIf with these practical considerations:

  • Import NgIf directly in a standalone component when the template uses *ngIf; importing CommonModule also works but brings unrelated entities. section 2.3.1
  • Treat nested ng-template and else chains as a readability and maintenance concern when conditions grow beyond a simple branch. section 10.1.1
  • Prefer Angular’s built-in @if and @else control-flow syntax for newer templates, especially when expressing multiple branches. section 10.1.1

How Modern Angular covers it

How deep it goes
Explains conditional DOM inclusion, standalone imports, and template branching, without descending into directive implementation internals.
Examples
Uses a login warning and nested ng-template branches to demonstrate simple conditions and multi-branch rendering.
What it assumes
Assumes familiarity with Angular templates and expressions while introducing structural directives and direct standalone directive imports.
What you can do after
Apply it via Angular standalone components to conditionally render validation feedback and other template content.
How it connects
Connects structural directives with standalone components, CommonModule, ng-template, ngFor, ngSwitch, and Angular built-in control flow.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern Angular. The section links point to the parts of the book it draws on.