Templates & LogicCore· 30 min read

Show & Hide with *ngIf

Add an element to the page only when a condition is true — and remove it when it is false.

What you will learn

  • Show or hide elements with *ngIf
  • Use an else block for the other case
  • Understand that *ngIf adds/removes from the page

Conditional HTML

*ngIf is a directive — a special attribute that changes how an element behaves. Put *ngIf on an element and Angular only puts it on the page when the condition is true.

A boolean that controls visibility
// component class
isLoggedIn = true;

Note: Output: (No visible output by itself.) This is just one true/false value, isLoggedIn, set to true. The template below uses it to decide whether a paragraph appears.

*ngIf shows the element only when true
<p *ngIf="isLoggedIn">Welcome back!</p>

Note: Output: Welcome back! Because isLoggedIn is true, the paragraph appears. Set it to false and the paragraph is removed from the page entirely — not just hidden with CSS.

An else block for the other case

You often want to show one thing or another. Pair *ngIf with an else and a named <ng-template>.

*ngIf with an else template
<p *ngIf="isLoggedIn; else guest">Welcome back!</p>
<ng-template #guest>
  <p>Please log in.</p>
</ng-template>

Note: Output (when isLoggedIn is false): Please log in. When the condition is true you see “Welcome back!”; when false, Angular shows the #guest template instead. The #guest is a template reference name.

Watch out: Do not forget the * star in *ngIf. It tells Angular this directive adds or removes the element. Without the star it will not work.

Tip: *ngIf truly removes the element from the page, which is great for things that should not exist yet (like a panel before data loads). If you only want to visually hide something, plain CSS display:none may be enough.

Q. What does *ngIf="false" do to an element?

Answer: *ngIf adds the element only when the condition is true. When false, Angular removes it from the DOM (the Document Object Model — the live tree of elements that makes up the page) completely.

✍️ Practice

  1. Use *ngIf to show a “Cart is empty” message only when a count is 0.
  2. Add an else block that shows the item count when the cart is not empty.

🏠 Homework

  1. Build a toggle: a button that flips a boolean, and a paragraph shown with *ngIf that appears or disappears.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →