Angular is a powerful framework that enables developers to build dynamic and scalable web applications. One of the key features that contribute to Angular’s flexibility is Directives. In this blog, we'll explore what Angular directives are, the different types, and how you can use them to enhance your applications.
Directives in Angular are special markers in the DOM (Document Object Model) that instruct Angular to do something with a DOM element, such as changing its appearance, behavior, or layout. They can be applied to elements in various ways, transforming the DOM without having to manipulate it directly using JavaScript or jQuery.
In simpler terms, directives are attributes or elements that allow developers to extend HTML with additional behavior.
There are three main types of directives in Angular:
Component directives are essentially Angular components. They come with a template, styles, and behavior. Components are the most common directives and are used to define a new, custom HTML tag. A component directive controls a section of the view by associating the view with its behavior.
Example:
@Component({ selector: 'app-hello-world', template: `<h1>Hello, World!</h1>` }) export class HelloWorldComponent {}
In the above example, app-hello-world
is a directive in the form of a custom element, and it renders a simple "Hello, World!" message.
Structural directives are responsible for altering the structure of the DOM by adding or removing elements. These directives are prefixed with an asterisk (*
) and often manipulate the DOM tree based on conditions.
The two most common structural directives are:
*ngIf
: Adds or removes an element based on a boolean expression.*ngFor
: Iterates over a collection and renders an element for each item.Example - *ngIf
:
<p *ngIf="isLoggedIn">Welcome, user!</p>
This will display the message "Welcome, user!" only if isLoggedIn
is true.
Example - *ngFor
:
html Copy code <ul> <li *ngFor="let item of items">{{ item }}</li> </ul>
Here, the *ngFor
directive loops through the items
array and creates a li
element for each item.
Other structural directives:
*ngSwitch
: Used for conditional rendering based on matching values.Attribute directives are used to change the appearance or behavior of an element. Unlike structural directives, they don’t add or remove elements. Instead, they alter the element they are attached to.
A well-known example of an attribute directive is ngClass
, which allows you to dynamically add or remove classes.
Example - ngClass
:
<p [ngClass]="{ 'active': isActive, 'inactive': !isActive }"> This is a paragraph. </p>
In this example, the paragraph will have the active
class if isActive
is true, otherwise it will have the inactive
class.
Creating a Custom Attribute Directive Creating your own attribute directive is straightforward. Let’s look at an example where we create a directive that changes the background color of an element.
Example:
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef, private renderer: Renderer2) {} @HostListener('mouseenter') onMouseEnter() { this.changeBgColor('yellow'); } @HostListener('mouseleave') onMouseLeave() { this.changeBgColor(null); } private changeBgColor(color: string) { this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', color); } }
This directive, appHighlight
, will highlight an element with a yellow background when the mouse hovers over it.
To use it in the template:
Copy code <p appHighlight>This paragraph will be highlighted on hover!</p>