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.
// 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.
<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>.
<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?
✍️ Practice
- Use
*ngIfto show a “Cart is empty” message only when acountis 0. - Add an
elseblock that shows the item count when the cart is not empty.
🏠 Homework
- Build a toggle: a button that flips a boolean, and a paragraph shown with
*ngIfthat appears or disappears.