Angular Directive Overview: Attribute Directives

Angular Directive Overview: Attribute Directives

Manipulate DOM properties, handle events, and apply dynamic styling to elements

This is part of a 3-part overview of Angular directives. Also see:

What Are Attribute Directives?

Attribute directives are a type of directive in Angular that change the appearance or behavior of an element, component, or another directive. Unlike structural directives, which add or remove elements from the DOM, attribute directives alter the existing elements. They are used to manipulate DOM properties, handle events, and apply dynamic styling to elements.

Attribute directives work by manipulating the DOM. They can change properties of DOM elements, bind input or output properties, and interact with events, enabling dynamic and responsive behavior.

Like other directives, attribute directives are reusable across different components in your Angular application, allowing for modular and maintainable code.

Common Examples of Attribute Directives:

NgStyle: The NgStyle directive allows you to dynamically set CSS styles on an element. You can bind it to an expression that evaluates to an object, where the object's keys are style names, and the values are the styles to be applied.

Let's assume that the div at the top of this example is found within ng-style-example.component.html.

<!-- Assume that textColor and textSize are available within this template's context -->
<div [ngStyle]="{'color': textColor, 'font-size': textSize + 'px'}">
  This text's style is dynamically set with NgStyle.
</div>

NgClass: The NgClass directive allows you add or remove CSS classes on an element dynamically based on the application's state or logic. You can bind it to an expression that evaluates to a string, array, or object that defines which classes to add or remove.

<!-- Assume that isActive and isDisabled are available within this template's context -->
<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">
  This div will have 'active' class if isActive is true and 'disabled' class if isDisabled is true.
</div>

Custom Attribute Directives:

You can create custom attribute directives to implement specific behavior that is not covered by Angular's built-in directives. For example, you might create a directive that automatically focuses an input field when a form is loaded or a directive that highlights text with a specific background color.

Creating a Custom Attribute Directive

Here's a simple example of creating a custom attribute directive in Angular that changes the background color of an element:

Define the Directive

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

@Directive({
  // The selector allows us to add appHighlight to any element
  selector: '[appHighlight]'
})
export class HighlightDirective implements OnChanges {
  @Input('appHighlight') highlightColor: string;

  constructor(private el: ElementRef) {}

  ngOnChanges(changes: SimpleChanges) {
    if (changes['highlightColor']) {
      this.changeBackgroundColor(this.highlightColor);
    }
  }

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

This directive, HighlightDirective, changes the background color of the element it is applied to. It uses the @Input decorator to accept a color value.

When the bound input changes, ngOnChanges will be executed, resulting in the native element background style also being updated.

Use the Directive in a Template:

<p appHighlight="lightblue">Highlighted text!</p>

To use an attribute directive, you simply add it as an attribute to a host element in your template. Angular then applies the directive's behavior to that element.

This applies the HighlightDirective to a paragraph element, setting its background color to light blue.

Key Takeaways About Attribute Directives

  • Attribute directives alter existing DOM elements. They do not create or remove elements from the DOM like structural directives do.

  • An instance of ElementRef is injected into the directive, which provides direct access to the host DOM element that the directive is attached to.

  • Like other directive types, the @Input decorator allows data to flow from the binding expression into the directive to be used within the directive. Our example above takes advantage of ngOnChanges to update the element when the binding value changes.

Summary

Attribute directives in Angular are essential for dynamically modifying the appearance and behavior of DOM elements, enabling developers to apply custom styles, manage attributes, and handle user interactions. Unlike structural directives, they don't alter the DOM structure but work on existing elements to enhance their functionality. By creating custom attribute directives, we can wrap complex behaviors, making the behavior that they add more reusable and easier to test.