0
0
Angularframework~5 mins

Why directives are needed in Angular

Choose your learning style9 modes available
Introduction

Directives help you add special behavior to HTML elements easily. They let you create reusable features that work like new HTML tags or attributes.

When you want to change how an element looks or behaves without rewriting HTML.
When you need to add custom features like showing/hiding parts of the page based on conditions.
When you want to reuse a piece of behavior across many parts of your app.
When you want to listen to user actions like clicks and respond in a clean way.
When you want to create your own HTML tags that do special things.
Syntax
Angular
import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appExample]'
})
export class ExampleDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    // directive logic here
  }
}

The @Directive decorator defines a directive and its selector.

The selector can be an attribute, element, or class to apply the directive.

Examples
This directive changes the background color of any element it is applied to.
Angular
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
  constructor(el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}
This directive creates a new HTML tag called <appCustomButton>.
Angular
@Directive({ selector: 'appCustomButton' })
export class CustomButtonDirective {
  // This directive can be used as a new HTML tag
}
Sample Program

This example shows a simple directive that changes the text color to red. When you add appRedText to a paragraph, the directive runs and changes its style.

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

@Directive({
  selector: '[appRedText]'
})
export class RedTextDirective {
  constructor(el: ElementRef) {
    el.nativeElement.style.color = 'red';
  }
}

@Component({
  selector: 'app-root',
  template: `<p appRedText>This text will be red because of the directive.</p>`
})
export class AppComponent {}
OutputSuccess
Important Notes

Directives help keep your HTML clean by moving behavior to reusable code.

They can manipulate the DOM safely using Angular's Renderer2 or ElementRef.

Always use directives for behavior, not for layout or styling alone.

Summary

Directives add special behavior to HTML elements.

They make your code reusable and easier to manage.

You can create new HTML tags or attributes with directives.