Saturday, July 4, 2026

Angular Directives – Complete Guide with All Examples

 A Directive in Angular is a class that adds behavior to HTML elements or changes the structure of the DOM.

Think of a directive as an instruction to Angular.

For example:

  • Show or hide an element

  • Repeat an element

  • Change colors

  • Disable buttons

  • Highlight text

  • Apply validation

  • Display content based on user role


Types of Directives

Angular has three types of directives.

Angular Directives

        │
        ├──────────────┐
        │              │
        ▼              ▼
Structural      Attribute
Directives      Directives
        │
        ▼
Component
(Technically a directive with a template)
TypePurposeExample
Component DirectiveCreates a view (template)<app-employee>
Structural DirectiveChanges the DOM structure*ngIf, *ngFor, *ngSwitch
Attribute DirectiveChanges appearance or behaviorngClass, ngStyle, custom directives

1. Component Directive

A component is actually a directive with its own HTML template.

Example:

@Component({
  selector: 'app-employee',
  template: `<h2>Employee Details</h2>`
})
export class EmployeeComponent { }

Use:

<app-employee></app-employee>

Output:

Employee Details

2. Structural Directives

Structural directives add or remove elements from the DOM.

They are written with *.


A. *ngIf

Displays an element only if the condition is true.

Example

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

Output

Welcome User

If:

isLoggedIn = false;

Output

Nothing is displayed.

Real-Time Example

Internet Banking

User Logged In

↓

Dashboard Visible

Otherwise

Please Login

ngIf with else

<div *ngIf="isLoggedIn; else loginPage">
    Welcome User
</div>

<ng-template #loginPage>
    Please Login
</ng-template>

B. *ngFor

Used to repeat HTML.

Component

employees = [
  "Mahesh",
  "Ravi",
  "Priya",
  "Kiran"
];

HTML

<ul>
    <li *ngFor="let emp of employees">
        {{emp}}
    </li>
</ul>

Output

Mahesh
Ravi
Priya
Kiran

Real-Time Example

Employee List

Employee Table

↓

100 Employees

↓

*ngFor repeats rows

ngFor with Index

<li *ngFor="let emp of employees; let i=index">
    {{i+1}} - {{emp}}
</li>

Output

1 - Mahesh
2 - Ravi
3 - Priya

ngFor with first and last

<li *ngFor="let emp of employees;
            let first=first;
            let last=last">

{{emp}}

{{first}}

{{last}}

</li>

Output

Mahesh   true    false
Ravi     false   false
Priya    false   true

C. ngSwitch

Component

role = "Admin";

HTML

<div [ngSwitch]="role">

    <p *ngSwitchCase="'Admin'">
        Admin Dashboard
    </p>

    <p *ngSwitchCase="'Employee'">
        Employee Dashboard
    </p>

    <p *ngSwitchDefault>
        Invalid User
    </p>

</div>

Output

Admin Dashboard

Real-Time Example

Login

Admin

↓

Admin Dashboard

Employee

Employee Dashboard


3. Attribute Directives

Attribute directives change appearance or behavior.


ngClass

Component

isActive = true;

HTML

<div
[ngClass]="{'active':isActive}">
Employee
</div>

CSS

.active{
color:red;
font-weight:bold;
}

Output

Employee (Red Color)

Real-Time Example

Employee Status

Active Employee

↓

Green Color

Inactive

Gray Color


ngStyle

<div
[ngStyle]="{

'color':'blue',

'font-size':'25px'

}">
Employee
</div>

Output

Blue Employee

Real-Time Example

Bank Balance

If balance is low

<div
[ngStyle]="{
'color':
balance<1000?
'red':'green'
}">
{{balance}}
</div>

Built-in Attribute Directive Example

Disable Button

<button
[disabled]="isSaving">
Save
</button>

Custom Attribute Directive

Suppose HR wants every employee card highlighted on mouse hover.

Generate Directive

ng g directive highlight

highlight.directive.ts

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

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

constructor(
private element:ElementRef){}

@HostListener('mouseenter')

mouseEnter(){

this.element.nativeElement.style.backgroundColor="yellow";

}

@HostListener('mouseleave')

mouseLeave(){

this.element.nativeElement.style.backgroundColor="white";

}

}

Use

<div appHighlight>

Employee Card

</div>

Output

Mouse Hover

↓

Yellow Background

Mouse Leave

↓

White Background

Custom Permission Directive

<div *appHasRole="'Manager'">

Salary Details

</div>

Logic

if(role==="Manager")
{
show=true;
}

Real-Time Example

Employee Login

Role

↓

Employee

↓

Salary Hidden

Manager

Salary Visible


Custom Disable Directive

<input appDisable />

Directive

this.element.nativeElement.disabled=true;

Output

Textbox Disabled

Real-Time Employee Portal

Employee Dashboard

        │
        ▼

*ngIf

Show Attendance

        │
        ▼

*ngFor

List Employees

        │
        ▼

ngClass

Green Active Employee

        │
        ▼

ngStyle

Salary Red

        │
        ▼

appHighlight

Hover Effect

        │
        ▼

appHasRole

Manager Only

Structural vs Attribute Directives

FeatureStructural DirectiveAttribute Directive
Changes DOMYesNo
Adds/Removes ElementsYesNo
Changes StyleNoYes
Uses *YesNo
Examples*ngIf, *ngFor, *ngSwitchngClass, ngStyle, appHighlight

Interview Questions

1. What is a directive in Angular?

A directive is a class that adds behavior to HTML elements or changes the DOM structure.

2. How many types of directives are there?

Three:

  • Component Directives

  • Structural Directives

  • Attribute Directives

3. What is the difference between *ngIf and [hidden]?

*ngIf[hidden]
Removes the element from the DOM when falseKeeps the element in the DOM but hides it using CSS

4. What is the difference between ngClass and ngStyle?

ngClassngStyle
Applies one or more CSS classesApplies inline CSS styles

5. Can we create custom directives?

Yes. Angular allows you to create reusable custom directives using the @Directive decorator.

Note for Angular 17+: The examples above use the classic structural directives (*ngIf, *ngFor, *ngSwitch), which are still widely used. Angular 17 also introduced new built-in control flow syntax (@if, @for, and @switch) as a modern alternative. Many existing projects and interview questions still use the * syntax, so it's important to understand both.

Creating a Custom Component in Angular with a Real-Time Example

 A Component is the basic building block of an Angular application. It combines HTML (UI), TypeScript (logic), and CSS (styles) into a reusable unit.

Real-Time Scenario

Suppose you are building an Employee Management System.

The application has multiple pages where employee information is displayed:

  • Dashboard

  • Employee List

  • Employee Details

  • HR Portal

Instead of writing the same HTML repeatedly, you create a reusable Employee Card Component.


Step 1: Create the Component

Using Angular CLI:

ng generate component employee-card

or

ng g c employee-card

Angular creates the following files:

employee-card/
│
├── employee-card.component.ts
├── employee-card.component.html
├── employee-card.component.css
└── employee-card.component.spec.ts

Step 2: Employee Card Component

employee-card.component.ts

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

@Component({
  selector: 'app-employee-card',
  templateUrl: './employee-card.component.html',
  styleUrls: ['./employee-card.component.css']
})
export class EmployeeCardComponent {

  @Input() employeeName: string = '';
  @Input() designation: string = '';
  @Input() salary: number = 0;
  @Input() department: string = '';

}

Explanation

  • @Component tells Angular this class is a component.

  • selector is the HTML tag used to display the component.

  • @Input() receives data from the parent component.


Step 3: Employee Card HTML

employee-card.component.html

<div class="employee-card">

    <h2>{{employeeName}}</h2>

    <p><strong>Designation:</strong> {{designation}}</p>

    <p><strong>Department:</strong> {{department}}</p>

    <p><strong>Salary:</strong> {{salary | currency:'INR'}}</p>

</div>

Step 4: CSS

employee-card.component.css

.employee-card{

    border:1px solid gray;

    padding:20px;

    border-radius:10px;

    width:300px;

    margin:15px;

    box-shadow:0 0 8px lightgray;

}

Step 5: Use the Component in App Component

app.component.ts

export class AppComponent {

    employee={

        name:'Mahesh',

        designation:'Senior Software Engineer',

        department:'IT',

        salary:85000

    };

}

app.component.html

<app-employee-card

    [employeeName]="employee.name"

    [designation]="employee.designation"

    [department]="employee.department"

    [salary]="employee.salary">

</app-employee-card>

Output

----------------------------------------
Mahesh

Designation : Senior Software Engineer

Department  : IT

Salary       : ₹85,000.00
----------------------------------------

Data Flow

App Component (Parent)

Employee Object

        │
        ▼

EmployeeCard Component

(@Input Properties)

        │
        ▼

HTML Template

        │
        ▼

Browser Output

Real-Time Banking Example

Imagine an Internet Banking application displaying multiple bank accounts.

Parent Component

accounts = [
  {
    accountNo: "1234567890",
    holder: "Ravi Kumar",
    balance: 250000
  },
  {
    accountNo: "9876543210",
    holder: "Priya Sharma",
    balance: 125000
  }
];

Parent HTML

<app-account-card
    *ngFor="let account of accounts"
    [accountNumber]="account.accountNo"
    [accountHolder]="account.holder"
    [balance]="account.balance">
</app-account-card>

Output

-------------------------
Ravi Kumar

Account : 1234567890

Balance : ₹250,000
-------------------------

-------------------------
Priya Sharma

Account : 9876543210

Balance : ₹125,000
-------------------------

The same component is reused for every account, making the UI modular and maintainable.


Advantages of Custom Components

  • Reusability: Create once, use anywhere.

  • Maintainability: Update one component to reflect changes everywhere.

  • Separation of Concerns: UI, logic, and styles remain organized.

  • Easy Testing: Components can be tested independently.

  • Scalability: Essential for large enterprise Angular applications.


Interview Questions

1. What is a custom component in Angular?

A custom component is a reusable UI element created by developers using the @Component decorator. It encapsulates HTML, TypeScript, and CSS into a single unit.

2. How do you create a component?

Using the Angular CLI:

ng generate component component-name

or

ng g c component-name

3. How do you pass data from a parent component to a child component?

By using the @Input() decorator.

@Input() employeeName: string = '';

4. How do you display a custom component?

By using its selector in another component's template.

<app-employee-card></app-employee-card>

5. Why are custom components important?

They promote code reuse, improve maintainability, simplify testing, and help organize applications into modular, reusable pieces.

Don't Copy

Protected by Copyscape Online Plagiarism Checker