0
0
AngularHow-ToBeginner · 3 min read

How to Use ngIf in Angular: Simple Conditional Rendering

Use the *ngIf directive in Angular templates to conditionally include or exclude elements based on a boolean expression. Place *ngIf="condition" on an element to show it only when the condition is true.
📐

Syntax

The *ngIf directive uses a boolean expression to decide if an element should be in the DOM. If the expression is true, Angular adds the element; if false, it removes it.

Example parts:

  • *ngIf="condition": The directive with a condition to check.
  • condition: A boolean or expression that returns true or false.
html
<div *ngIf="isVisible">Content to show only if isVisible is true</div>
Output
Content to show only if isVisible is true
💻

Example

This example shows a button that toggles a message. The message appears only when the condition is true using *ngIf.

typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-ngif-example',
  template: `
    <button (click)="toggle()">Toggle Message</button>
    <p *ngIf="showMessage">Hello! This message is visible.</p>
  `
})
export class NgIfExampleComponent {
  showMessage = false;

  toggle() {
    this.showMessage = !this.showMessage;
  }
}
Output
Button labeled 'Toggle Message'. When clicked, the text 'Hello! This message is visible.' appears or disappears.
⚠️

Common Pitfalls

Common mistakes when using *ngIf include:

  • Forgetting the asterisk *, which is required for structural directives.
  • Using ngIf without a boolean expression, causing errors.
  • Trying to use *ngIf on multiple elements without wrapping them in a container.

Correct usage ensures Angular properly adds or removes elements from the DOM.

html
/* Wrong: missing asterisk */
<div ngIf="isVisible">This will not work</div>

/* Right: with asterisk */
<div *ngIf="isVisible">This works correctly</div>
📊

Quick Reference

FeatureDescription
*ngIf="condition"Shows element only if condition is true
*ngIf="!condition"Shows element only if condition is false
Use with ngIf for else blocks
Multiple elementsWrap in a container to apply *ngIf

Key Takeaways

Use *ngIf with a boolean condition to control element visibility in Angular templates.
Always include the asterisk (*) before ngIf to make it a structural directive.
Wrap multiple elements in a container when applying *ngIf to avoid errors.
Use *ngIf to add or remove elements from the DOM, improving performance.
Remember *ngIf removes elements completely, unlike CSS visibility.