Directives play a crucial role in shaping your user interface.
In this guide, you will learn about Angular Directives, covering the basics, types, and examples of built-in Directives, as well as creating custom ones.
By the end of this article, you’ll have a solid understanding of Directives to build robust and dynamic Angular applications.
What are Directives?
A directive in angular is a class that adds behavior to an element in your application.
It’s a way to extend the functionality of an HTML element, allowing you to create custom components, modify element behavior, or even create entirely new elements.
Think of Directives in Angular like special instructions that you can give to HTML elements.
They’re like custom attributes that extend the behavior of an element, allowing you to do more with it than what’s normally possible.
For example, if you want to create a button that shows a tooltip when hovered over, you can use a Directive to add that functionality.
Directives are essentially functions that run on specific elements and change their behavior or appearance in some way.
They’re super useful for creating reusable UI components and adding dynamic effects to your application without having to write a ton of code.
By using Directives, you can make your HTML more powerful and interactive, making your Angular app more engaging and user-friendly.
Types of Directives
There are three main types of directives in Angular:
A. Component Directives,
B. Attribute Directives, and
C. Structural Directives.
Type | Description |
Component Directives | Used to create custom components |
Attribute Directives | Used to modify element behavior |
Structural Directives | Used to manipulate the DOM structure |
Custom Directives | Used to create custom functionality |
Types of directives are categorized based on their purpose and functionality.
You can use these directives to create custom components, modify element behavior, or even manipulate the DOM structure.
Built-in Directives
Built-in directives are pre-defined directives that come bundled with the Angular framework, which means you don’t need to create them from scratch.
These directives are designed to perform common tasks, such as manipulating the DOM, handling events, and controlling the flow of data.
For example, one of the most commonly used built-in directives is ngIf
.
This directive allows you to conditionally render an element based on a boolean expression.
For instance, if you want to display a message only when a user is logged in, you can use ngIf
like this
<div *ngIf="isLoggedIn"> Welcome, {{username}}! </div>
In this example, the div
element will only be rendered if the isLoggedIn
property is true
.
Other directives such as ngFor
and ngSwitch
are used to manipulate the DOM structure, allowing you to conditionally iterate over arrays, or dynamically show elements based on condition. ngIf
, ngFor
and ngSwitch
are all examples of structural directives since they can manipulate the DOM structure.
Creating a Custom Directive
Many Angular developers need to create custom directives to achieve specific functionality in their applications.
To create a custom directive, you’ll need to follow these basic steps:
Step | Description |
---|---|
1 | Create a new directive class |
2 | Decorate the class with the @Directive decorator |
3 | Define the directive’s properties (e.g. selector, template) |
4 | Implement the directive’s logic |
Creating a custom directive requires you to decorate your class with the @Directive
decorator.
This decorator is used to configure the directive’s metadata.
Selector is one of the most important properties of the @Directive
decorator.
It specifies the HTML element that the directive will be attached to.
For example, if you set the selector to `[appHighlight]`’, your directive will be applied to any element with the attribute appHighlight
.
Custom Directive Example
Guide yourself through the following example code to get a better understanding of how to create a basic custom directive:
import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[appHoverHighlight]' }) export class HoverHighlightDirective { @Input() defaultColor: string = 'yellow'; @Input('appHoverHighlight') highlightColor: string = 'blue'; constructor(private el: ElementRef) {} @HostListener('mouseenter') onMouseEnter() { this.highlight(this.highlightColor || this.defaultColor); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } }
In this example,
@Directive decorator marks the class as a directive and specifies the selector [appHoverHighlight]
.
ElementRef grants direct access to the DOM element.
@HostListener enables you to listen for the mouseenter
and mouseleave
events on the host element and call the appropriate methods.
@Input specifies that the variable is an input property and allows the directive to accept inputs to configure the highlight colors.
Using Custom Directive in a Template
Assuming you’ve created a custom Directive, you can use it in an HTML template by adding the Directive’s selector to an element.
For example, if your Directive has a selector appHoverHighlight
as in the above example, you can use it like this:
<!-- app.component.html --> <p appHoverHighlight="lightblue" defaultColor="yellow"> Hover over this text to see the highlight effect. </p>
. This will apply the Directive’s behavior to the div element.
Ensure that the directive is declared in the component’s module as shown below else it will not work
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HoverHighlightDirective } from './hover-highlight.directive'; @NgModule({ declarations: [ AppComponent, HoverHighlightDirective ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Attribute Directives
Your application’s HTML elements can be modified and extended using Attribute Directives.
These directives alter the appearance or behavior of an element by adding or modifying attributes.
They are useful when you want to apply a consistent style or behavior across multiple elements, or when you want to conditionally apply an attribute based on some logic.
ngStyle
and ngClass
are two commonly used built-in Attribute Directives in Angular. ngStyle
allows you to dynamically set CSS styles on an element, while ngClass
enables you to dynamically add or remove CSS classes.
A great example of using ngStyle
is when you want to conditionally change the color of an element based on some logic.
For instance, you can use ngStyle
to change the text color of a paragraph to red if a certain condition is met.
Directive Best Practices
Unlike other Angular components, Directives are not meant to be complex or have a lot of logic.
They are meant to be simple and focused on a specific task.
Here are some best practices that you can follow while writing Directives.
- Keep your Directives simple and focused on a single task.
- Avoid complex logic or computations in your Directives.
- Use Directives to extend the functionality of existing HTML elements.
- Knowing when to use a Directive versus a Component can make a big difference in your application’s performance and maintainability.
Conclusion
In this article, we learned about Angular Directives, different types of Directives, how to create custom ones, and how to use them effectively in your templates.