Angular ngIf Directive Tutorial 🎯

beginner
7 min

Angular ngIf Directive Tutorial 🎯

Welcome to the ngIf Directive lesson! In this tutorial, we'll explore one of Angular's essential features - the ngIf directive. Let's dive in!

What is ngIf Directive? 📝

The ngIf directive is a built-in Angular directive that lets you conditionally render Angular components based on a boolean expression. It's a powerful tool that helps you create dynamic and responsive applications.

Why use ngIf Directive? 💡

  • Simplifies conditional rendering
  • Makes your code cleaner and easier to read
  • Reduces unnecessary rendering, improving app performance

Basic Usage 💡

To use ngIf, simply apply it to an element in your Angular template, and Angular will handle the rest.

html
<div *ngIf="showDiv; else noDiv"> This div will be shown if showDiv is true. </div> <ng-template #noDiv> This template will be shown if showDiv is false. </ng-template>

In the above example, the div will be shown if the showDiv variable is true, and the noDiv template will be shown if showDiv is false.

Ternary Operator and ngIf 💡

You can also use the ternary operator with ngIf for simple conditions:

html
<div *ngIf="condition ? true : false"> This div will be shown if condition is true. </div>

ngIf with Properties 💡

You can use ngIf with properties, too:

html
<div *ngIf="myObject.property"> This div will be shown if myObject.property is truthy. </div>

ngIf and ngFor Together 💡

You can use ngIf and ngFor together to create dynamic lists:

html
<div *ngFor="let item of items; index as i; *ngIf=item.visible"> {{ i }}: {{ item.name }} </div>

In this example, the items will only be rendered if item.visible is truthy.

ngIf and Change Detection 💡

ngIf affects Angular's change detection. When an ngIf condition changes, the entire component tree is checked for changes. To optimize performance, you can use trackBy function:

typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-example', template: ` <div *ngFor="let item of items; trackBy: trackByIndex; *ngIf=item.visible"> {{ item.name }} </div> `, }) export class ExampleComponent { items = [ { name: 'Item 1', visible: true }, { name: 'Item 2', visible: false }, { name: 'Item 3', visible: true }, ]; trackByIndex(index: number, item: any) { return index; } }

In the above example, the trackByIndex function ensures that Angular only checks the changed items when the ngIf condition changes.

Quiz 📝

Quick Quiz
Question 1 of 1

What does the ngIf directive do in Angular?

That's all for now! In the next lesson, we'll explore another powerful Angular directive - ngSwitch. Until then, happy coding! 🚀