Exploring Angular Directives: Creating Custom Directives

Angular is a powerful front-end framework renowned for its versatility, providing various tools for building dynamic web applications. Angular Directives, which let programmers extend HTML and create reusable parts or behaviors, are one of its main characteristics. In this blog post, we’ll explore what Angular Directives are, the different types of Angular Directives, and how to create custom Angular Directives.

What are Angular Directives?

Angular Directives are special tokens in the DOM that tell Angular to do something with a DOM element (or even its children). They can manipulate the structure and behavior of the DOM and are crucial for creating dynamic applications.

Types of Angular Directives

  1. Components: These are Angular Directives with a template. They are the most common type of directives and form the building blocks of Angular applications.
  2. Attribute Directives: These change the appearance or behavior of a DOM element. They look like regular HTML attributes but add special behavior to the element.
  3. Structural Directives: They add or remove items to alter the DOM layout. They use asterisks (*) to differentiate themselves, such as *ngIf or *ngFor.

Creating a Custom Directive

Custom Angular Directives can encapsulate complex behavior and make it reusable across your application. Let’s create a simple attribute directive that changes the text color of an element when clicked.

Step 1: Generate the Directive

Use Angular CLI to generate a new directive. Open your terminal and run:

ng generate directive TextColor

This command creates two files:

text-color.directive.ts and text-color.directive.spec.ts.

Step 2: Implement the Directive Logic

Open the text-color.directive.ts file and implement the logic to change the text color on click.

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

@Directive({
 selector: '[appTextColor]'
})
export class TextColorDirective {
 @Input('appTextColor') textColor: string;

constructor(private el: ElementRef) {
 // Set default text color if none is provided
 this.textColor = this.textColor || 'blue';
 }

@HostListener('click') onClick() {
 this.changeTextColor(this.textColor);
 }

private changeTextColor(color: string) {
 this.el.nativeElement.style.color = color;
 }
}

Explanation

  • @Directive: This decorator marks the class as a directive.
  • selector: This is the CSS selector that identifies the directive in a template.
  • ElementRef: A service that gives direct access to the DOM element.
  • @HostListener: Decorators that listen to DOM events and trigger the associated method.

In this Directive:

  • We inject ElementRef to get a reference to the element the directive is applied to.
  • We define a host listener for the click event to handle the click event.
  • The changeTextColor method updates the text color of the element.

Related read: Creating Reusable Angular Components with the NgTemplateOutlet Directive

Level Up Your Angular Expertise. Hire Skilled Angular Developers!

Step 3: Use the Directive in a Component

To use this directive, add it to a component’s template and specify a color if desired.

<p appTextColor="red">Click this text to change its color to red.</p>
<p appTextColor>Click this text to change its color to blue (default).</p>

Step 4: Register the Directive

Ensure that your directive is declared in an Angular module. Open app.module.ts and add the directive to the declarations array.

import { TextColorDirective } from './text-color.directive';

@NgModule({
declarations: [
  TextColorDirective
],
// Other module properties
})
export class AppModule { }
coma

Conclusion

Creating custom Angular Directives allows us to encapsulate and reuse functionality across your application. In this example, we created a simple directive that changes the text color of an element when clicked. Custom Angular Directives can be as simple or as complex as needed, offering a powerful way to enhance your application’s interactivity and maintainability.

By mastering the creation and use of custom Angular Directives, we can significantly improve the flexibility and reusability of your Angular applications. Happy coding!

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?