Skip to main content

What does the ngIf directive do?

The *ngIf directive in Angular is a structural directive that conditionally adds or removes an element from the DOM based on a boolean expression.

How it works:

  1. If the condition is true (true), Angular inserts the element into the DOM.
  2. If the condition is false (false), the element is removed from the DOM completely.
  3. Supports additional branching via else.

Example:

html
<p *ngIf="isVisible">This text is shown only if isVisible = true</p> <ng-template #elseBlock> <p>Text when false</p> </ng-template> <p *ngIf="isVisible; else elseBlock">Conditional text</p>

Conclusion: *ngIf controls the presence of elements in the DOM, not just their visibility via CSS.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.