Master Angular From Scratch

Learn Angular with clear, interactive, and structured lessons for beginners and developers.

ANGULAR COURSE SYLLABUS
1. Angular Introduction
Angular Introduction Angular History Angular Fundamentals Angular Architecture Component-Based Angular
2. Angular Setup
Angular Setup Introduction Installing Node.js Installing Angular CLI Creating an Angular Application Angular Project Structure
3. Components
Components Overview Component Anatomy Creating Components Component Selector Component Template Component Styles Component Metadata Standalone Components Parent and Child Components Reusable Components
4. Templates
Templates Introduction Template Syntax Template Expressions Template Statements Template Reference Variables ng-template ng-container ngTemplateOutlet Built-in Control Flow
5. Data Binding
Data Binding Introduction Interpolation Binding Property Binding Event Binding Two-Way Data Binding Class & Style Binding
6. Directives
Directives Introduction Attribute Directives Structural Directives Custom Directives
7. Pipes
Pipes Introduction Built-in Pipes Parameterized Pipes Chaining Pipes Custom Pipes
8. Event Handling
Event Handling Introduction DOM Events Event Binding Syntax Event Object Passing Data to Event Handlers
9. Input & Output
Component Communication @Input @Output EventEmitter
10. Lifecycle Hooks
Lifecycle Hooks Introduction ngOnInit ngOnChanges ngAfterViewInit ngOnDestroy
11. Services
Services Introduction Creating Angular Services Using Services in Components Sharing Data Through Services Service Scope
12. Dependency Injection
Dependency Injection Introduction Injecting Dependencies InjectionToken Provider Configuration
13. Routing
Routing Introduction Route Configuration RouterLink & Navigation Route Parameters Child Routes Route Guards
14. Forms
Angular Forms Introduction Template-Driven Forms Reactive Forms Form Validation Form Submission & Error Handling
15. HttpClient
HttpClient Introduction Configuring HttpClient GET Request POST, PUT & DELETE Requests Headers & Parameters HTTP Error Handling
16. Observables
Observables Introduction Creating & Subscribing to Observables Observable Data Streams Observable Operators Subscription Management
17. RxJS
RxJS Introduction RxJS Operators Transformation & Filtering Combining Observables Higher-Order Mapping Subjects
18. API Integration
API Integration Introduction Connecting Angular with REST API Consuming API Data CRUD API Integration API Response & Error Handling

Custom Directives

Learn how to create reusable Angular directives for custom behavior and interaction with HTML elements.

What are Custom Directives?

Custom directives are developer-created Angular directives used to add reusable behavior to HTML elements.

They are useful when the same DOM behavior or UI interaction needs to be used in multiple places in an application.

Custom Directive Flow

1
Create

Create a directive using the Angular CLI.

→
2
Define

Define the required directive behavior.

→
3
Apply

Apply the directive to an HTML element.

→
4
Reuse

Reuse the behavior wherever it is required.

Why Create Custom Directives?

R
Reusable

The same behavior can be reused on multiple elements.

C
Custom Behavior

Implement behavior specific to your application.

M
Maintainable

Keep common DOM behavior in one place.

U
UI Enhancement

Improve the interaction and appearance of UI elements.

Creating a Custom Directive

Angular CLI can generate a directive automatically.

CLI Command
ng generate directive highlight

Short form:

CLI
ng g directive highlight

Generated Directive

highlight.directive.ts
import { Directive } from '@angular/core';

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

}
Explanation:
The @Directive decorator tells Angular that this class represents a directive.

Directive Selector

The selector defines how the custom directive is applied in the HTML template.

Directive
@Directive({
    selector: '[appHighlight]'
})
HTML
<p appHighlight>
    Angular Training
</p>
Result:
Angular applies the directive to the paragraph because it contains the appHighlight attribute.

Using ElementRef

ElementRef provides access to the native element on which the directive is applied.

highlight.directive.ts
import { Directive, ElementRef } from '@angular/core';

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

    constructor(private element: ElementRef) {

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

    }

}
Result:
The element using appHighlight receives a yellow background.

Using HostListener

HostListener allows a directive to respond to events generated by its host element.

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

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

    constructor(private element: ElementRef) {
    }

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

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

}
HTML
<p appHighlight>
    Move the mouse over this text
</p>
Result:
The background changes when the mouse enters the element and returns to normal when the mouse leaves.

Passing Data to a Directive

A custom directive can receive values from the component using an input property.

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

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

    @Input() appHighlight = '';

    constructor(private element: ElementRef) {
    }

}
HTML
<p [appHighlight]="'lightblue'">
    Angular Training
</p>

Complete Highlight Directive Example

highlight.directive.ts
import {
    Directive,
    ElementRef,
    HostListener
} from '@angular/core';

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

    constructor(private element: ElementRef) {
    }

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

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

}
student.component.html
<h3 appHighlight>
    Pradnya
</h3>

<p appHighlight>
    Angular Full Stack Student
</p>

Pradnya

Angular Full Stack Student

Move the mouse over an element to see the directive behavior.

Common Use Cases

H
Highlighting

Highlight elements on hover or based on conditions.

F
Focus

Automatically focus an input element.

A
Animation

Add reusable interaction or animation behavior.

V
Validation

Add reusable UI behavior around validation.

Built-in vs Custom Directives

Type Purpose Example
Built-in Provided by Angular ngClass
Built-in Controls DOM structure *ngIf
Custom Application-specific behavior appHighlight

Best Practices

  • Give custom directives clear and meaningful names.
  • Keep a directive focused on one reusable behavior.
  • Use HostListener for host element events.
  • Use inputs when the directive needs configurable values.
  • Avoid putting large business logic inside directives.
  • Reuse directives when the same UI behavior appears in multiple places.

Summary

  • Custom directives provide reusable application-specific behavior.
  • Use the Angular CLI to generate directives quickly.
  • @Directive defines a custom directive.
  • ElementRef provides access to the host element.
  • HostListener allows the directive to respond to events.
  • Inputs can be used to pass values into a directive.
  • Custom directives help keep UI behavior reusable and maintainable.