Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Angular Directives – Complete In-Depth Tutorial

🔷 What is a Directive in Angular?

A directive is a special instruction in Angular that changes the behavior, appearance, or structure of DOM elements.

👉 In simple words:

Directives teach HTML new tricks.


🧩 Types of Directives in Angular

Angular provides three types of directives:

  1. Structural Directives

  2. Attribute Directives


🧱 1️⃣ Structural Directives (Change DOM Structure)

📌 Structural directives add, remove, or manipulate elements in the DOM.

👉 They are identified by * (asterisk)

🔹 Why * is used?

The * tells Angular:

“This directive will change the structure of the DOM.”

Internally, Angular converts it into <ng-template>.


✅ Common Structural Directives



Conditionally adds/removes elements.

<p *ngIf="isLoggedIn">Welcome User</p>

✔ True → element exists
❌ False → element removed from DOM


🔸 *ngFor

Used to loop through collections.

<ul> <li *ngFor="let item of items; index as i"> {{ i }} - {{ item }} </li> </ul>
items = ['Angular', 'React', 'Vue'];

🔸 *ngSwitch

Used for multiple conditions.

<div [ngSwitch]="role"> <p *ngSwitchCase="'admin'">Admin Panel</p> <p *ngSwitchCase="'user'">User Dashboard</p> <p *ngSwitchDefault>Guest</p> </div>

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  // Used for ngIf
  isLoggedIn: boolean = false;
  // Used for ngFor
  students: string[] = ['Rahul', 'Amit', 'Neha', 'Pooja'];
  toggleLogin() {
    this.isLoggedIn = !this.isLoggedIn;
  }
}
📄 Template File – app.component.html
🔹 Example 1: *ngIf (Condition Based Rendering)
<h2>*ngIf Example</h2>
<button (click)="toggleLogin()">
  Toggle Login
</button>
<p *ngIf="isLoggedIn">
  Welcome! You are logged in.
</p>
<p *ngIf="!isLoggedIn">
  Please login first.
</p>
<hr />

🔹 Example 2: 
*ngFor (Loop / List Rendering)
<h2>*ngFor Example</h2>
<ul>
  <li *ngFor="let student of students; index as i">
    {{ i + 1 }}. {{ student }}
  </li>
</ul>
<hr />


Example of NgSwitch:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

  role: string = 'guest';

  changeRole(selectedRole: string) {
    this.role = selectedRole;
  }
}
📄 Template File – app.component.html

🔹 Role Selection Buttons

<h2>ngSwitch Example</h2> <button (click)="changeRole('admin')">Admin</button> <button (click)="changeRole('user')">User</button> <button (click)="changeRole('guest')">Guest</button>



<div [ngSwitch]="role"> <div *ngSwitchCase="'admin'"> <h3>Admin Panel</h3> <p>You have full access.</p> </div> <div *ngSwitchCase="'user'"> <h3>User Dashboard</h3> <p>Limited access.</p> </div> <div *ngSwitchDefault> <h3>Guest Page</h3> <p>Please login to continue.</p> </div> </div>

🧠 Structural Directive Summary

DirectivePurpose
*ngIfConditional rendering
*ngForLoop rendering
*ngSwitchMultiple conditions

🎨 2️⃣ Attribute Directives (Change Appearance/Behavior)

📌 Attribute directives do not remove elements
They modify properties, styles, or behavior of elements.

👉 Used without *


✅ Common Attribute Directives



🔹 ngClass

Dynamically add/remove CSS classes.

<p [ngClass]="{ active: isActive, error: hasError }"> Status Text </p>

🔹 ngStyle

Apply dynamic inline styles.

<p [ngStyle]="{ color: isError ? 'red' : 'green' }"> Message </p>

🔹 [disabled], [hidden]

Control element properties.

<button [disabled]="isSubmitting">Submit</button>

🧠 Attribute Directive Summary

DirectivePurpose
ngClassCSS class binding
ngStyleInline style binding
[hidden]Show/Hide (CSS)

⚠️ *ngIf vs [hidden] (Interview Favorite)

Feature*ngIf[hidden]
DOM Removal✅ Yes❌ No
PerformanceBetterLess
VisibilityElement destroyedCSS hidden


Post a Comment

0 Comments