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.

A directive is a class that adds behavior or changes the appearance/structure of DOM elements.

In Angular, directives are broadly divided into:

👉 In simple words:

Directives teach HTML new tricks.

Component = Directive + Template 

A component controls a view, while a directive generally adds behavior to an existing element.


TypePurposeExample
ComponentCreates UI/view@Component
Attribute DirectiveChanges behavior/appearance[ngClass], [ngStyle]
Structural DirectiveChanges DOM structure*ngIf, *ngFor




Important Angular 21 note

Modern Angular uses the built-in control-flow syntax such as:

@if
@for
@switch

instead of relying on *ngIf and *ngFor for new code.

However, structural directives are still important to understand, because many existing Angular applications and libraries use them.



🧩 Types of Directives in Angular

Angular provides three types of directives:

  1. Structural Directives

  2. Attribute Directives 

  3. Component 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>

Angular 21 Control Flow

For new Angular 21 applications, teach the modern syntax:

@if (isLoggedIn) {
  <div>Welcome User</div>
}

Instead of:

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

Similarly:

Old

<ul>
  <li *ngFor="let product of products">
    {{ product.name }}
  </li>
</ul>

Modern Angular

<ul>
  @for (product of products; track product.id) {
    <li>
      {{ product.name }}
    </li>
  }
</ul>

This distinction is worth emphasizing in an Angular 21 class:


🧠 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.

.css

p {

  padding: 10px;

  font-weight: bold;

  border: 1px solid #ccc;

  width: 200px;

  text-align: center;

}


/* Active Style */

.active {

  background-color: lightgreen;

  color: green;

}


/* Error Style */

.error {

  background-color: #ffdddd;

  color: red;

}


.ts

isActive:boolean = true;

  hasError:boolean=false


.html

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

🔹 ngStyle

Apply dynamic inline styles.


.ts file

role: string = 'guest';

 

  changeRole(s:string)

  {

     this.role=s

  }


.html file

<button (click)="changeRole('admin')" [ngStyle]="{'background-color':role==='admin'?'yellow':'red'}">Admin</button>

<button (click)="changeRole('user')">User</button>

<button (click)="changeRole('guest')">Guest</button>

<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
  


Creating a Custom Attribute Directive

Now move to the most important practical part.

Let's create:

highlight

directive.

Create it:

ng generate directive highlight

or:

ng g d highlight

Angular will generate something similar to:

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

@Directive({
  selector: '[appHighlight]'
})
export class Highlight {
}

11. Using the Directive

HTML:

<p appHighlight>
  Move mouse over me
</p>

The important point is:

selector: '[appHighlight]'

The square brackets mean that the directive is used as an attribute.


12. ElementRef

To access the host DOM element:

import {
  Directive,
  ElementRef
} from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class Highlight {

  constructor(private element: ElementRef) {
    this.element.nativeElement.style.backgroundColor = 'yellow';
  }
}

HTML:

<p appHighlight>
  Angular Directive
</p>

The paragraph becomes yellow.


13. Why ElementRef?

Explain:

ElementRef

provides a reference to the DOM element on which the directive is applied.

For example:

<button appHighlight>

The directive's ElementRef refers to that button.

ATTACH EVENT ON DIRECTIVE:

import {
  Directive,
  ElementRef,
  HostListener
} from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class Highlight {

  constructor(private element: ElementRef) {
  }

  @HostListener('mouseenter')
  onMouseEnter() {
    this.element.nativeElement.style.backgroundColor = 'yellow';
  }

  @HostListener('mouseleave')
  onMouseLeave() {
    this.element.nativeElement.style.backgroundColor = '';
  }
}

Create Visited / Not Visited Using Custom Directive

In Angular 21, we can create a custom attribute directive to change the background color of an element based on whether the user has visited (clicked) it.

For example:

  • Not Visited: Red background

  • Visited: Green background

We will use @Directive, @HostBinding, and @HostListener.

Understanding the directive

Angular feature

Purpose

@Directive

Creates a custom directive

@HostBinding

Binds a property to the host element

@HostListener

Listens to events on the host element

isVisited

Stores whether the element has been clicked

Step 1: Create a custom directive

Run the following Angular CLI command:

ng generate directive visited

This creates a file named visited.ts.

Step 2: Write the directive code

visited.ts

import {
  Directive,
  HostBinding,
  HostListener
} from '@angular/core';

@Directive({
  selector: '[appVisited]',
  standalone: true
})
export class Visited {

  // Initially, the element is not visited
  isVisited: boolean = false;

  // Change background color
  @HostBinding('style.backgroundColor')
  get backgroundColor(): string {
    return this.isVisited ? 'green' : 'red';
  }

  // Change text color
  @HostBinding('style.color')
  textColor: string = 'white';

  // Handle click event
  @HostListener('click')
  onClick(): void {
    this.isVisited = true;
  }
}

Step 3: Import directive into component

app.ts

import { Component } from '@angular/core';
import { Visited } from './visited';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [Visited],
  templateUrl: './app.html'
})
export class App {

}

Step 4: Use directive in HTML

app.html

<h2>Angular 21 Custom Directive Example</h2>

<button appVisited>
  Angular
</button>

<button appVisited>
  React
</button>

<button appVisited>
  Java
</button>

<button appVisited>
  Python
</button>


Without Directive Normal also

Yes. If you want Visited / Not Visited on a menu, for example:

Home | About | Courses | Contact

and when the user clicks a menu item it should become Visited, you can do it normally without a directive.

app.ts

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

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

  selectedMenu = '';

  menuItems = [
    'Home',
    'About',
    'Courses',
    'Contact'
  ];

  visitMenu(menu: string) {
    this.selectedMenu = menu;
  }
}

app.html

<nav>
  <ul>
    @for (menu of menuItems; track menu) {
      <li>
        <a
          href="#"
          (click)="visitMenu(menu); $event.preventDefault()"
          [class.visited]="selectedMenu === menu"
          [class.not-visited]="selectedMenu !== menu">

          {{ menu }}

          <span>
            {{ selectedMenu === menu ? '(Visited)' : '(Not Visited)' }}
          </span>

        </a>
      </li>
    }
  </ul>
</nav>

app.css

nav ul {
  display: flex;
  gap: 20px;
  list-style: none;
}

nav a {
  text-decoration: none;
  padding: 10px 15px;
  border-radius: 5px;
}

.not-visited {
  color: black;
  background: #eee;
}

.visited {
  color: white;
  background: green;
}





إرسال تعليق

1 تعليقات

  1. I have created calculator app in js but i can not know how to convert js code in ts codes this is the code function Solve(val) {
    var v = document.getElementById('result');
    v.value += val;
    }
    function Result() {
    var num1 = document.getElementById('result').value;
    try {
    var num2 = eval(num1.replace('x', '*'));
    document.getElementById('result').value = num2;
    } catch {
    document.getElementById('result').value = 'Error';
    }
    }
    function Clear() {
    var inp = document.getElementById('result');
    inp.value = '';
    }
    function Back() {
    var ev = document.getElementById('result');
    ev.value = ev.value.slice(0, -1);
    }
    document.addEventListener('keydown', function (event) {
    const key = event.key;
    const validKeys = '0123456789+-*/.%';
    if (validKeys.includes(key)) {
    Solve(key === '*' ? 'x' : key);
    } else if (key === 'Enter') {
    Result();
    } else if (key === 'Backspace') {
    Back();
    } else if (key.toLowerCase() === 'c') {
    Clear();
    }
    }); please tell me for this

    ردحذف

POST Answer of Questions and ASK to Doubt