Skip to main content

Understanding Directives

Directives are one of the most powerful features of Angular. They allow you to create custom HTML-like elements and attributes that can modify the behavior of an element or its children. In this tutorial, we will explore what directives are, how to use them, and how to create your own.

What are Directives?

In Angular, directives are classes that can change the behavior or appearance of elements in your HTML. They can be thought of as instructions that tell Angular how to process, manipulate, and manage elements and their attributes.

Angular has three kinds of directives:

  1. Component Directives: These are directives with a template. This is what we generally refer to when we talk about Angular components.

  2. Attribute Directives: These directives change the appearance or behavior of an element, component, or another directive.

  3. Structural Directives: These directives change the DOM layout by adding and removing DOM elements.

Using Built-in Directives

Angular provides a set of built-in directives that you can use right away in your projects. Let's take a look at a few examples.

Attribute Directives

One of the most commonly used attribute directives is ngStyle. This directive allows you to set CSS styles directly from your component logic. Here's how it works:

<div [ngStyle]="{'font-size': '24px'}">This is some text.</div>

In this example, we're using ngStyle to set the font-size of the div element to 24px.

Structural Directives

Structural directives allow you to manipulate the DOM. They can add, remove, or manipulate elements. One of the most commonly used structural directives is ngIf.

<div *ngIf="showText">This text will only appear if showText is true</div>

In this example, the div will only be added to the DOM if the showText property is true.

Creating Custom Directives

While built-in directives cover a lot of common use-cases, sometimes you will need to create your own. Luckily, Angular makes this process quite straightforward.

To create a directive, you'll need to create a new class and decorate it with the @Directive decorator. Here's an example of a simple custom directive:

import { Directive } from '@angular/core';

@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
// your logic goes here
}

In this example, we're creating a new directive called HighlightDirective. This directive can be used on any element by adding the appHighlight attribute.

Conclusion

Directives are a powerful tool in Angular. They allow you to create reusable, composable pieces of functionality that can be used throughout your application. Whether you're using built-in directives like ngStyle and ngIf, or creating your own custom directives, understanding how directives work will help you write more efficient, maintainable Angular code.