Skip to main content

Overview

The @Directive decorator marks a class as an Angular directive and provides configuration metadata. Directives attach custom behavior to elements in the DOM.

Signature

Parameters

Directive
required
Configuration object that specifies how the directive should be processed and used.

Directive Metadata

selector

string
CSS selector that identifies elements to which this directive is applied.

standalone

boolean
default:"true"
When true, the directive does not need to be declared in an NgModule.

inputs

string[] | {name: string, alias?: string, required?: boolean, transform?: Function}[]
Input properties that accept data binding.

outputs

string[]
Output properties that emit events.

providers

Provider[]
Services available for dependency injection in this directive.

exportAs

string
Name for template variable references.
Usage: <div appHighlight #h="highlight"></div>

host

{[key: string]: string}
Map of host element bindings, properties, attributes, and events.

hostDirectives

Type<unknown>[] | {directive: Type<unknown>, inputs?: string[], outputs?: string[]}[]
Directives to apply to the host element, enabling directive composition.

Attribute Directive Example

highlight.directive.ts
Usage:

Structural Directive Example

unless.directive.ts
Usage:

Host Bindings Example

button-role.directive.ts

Directive Composition

menu-item.directive.ts
Usage:

Input Transformation

auto-id.directive.ts

Querying Directive Instances

parent.component.ts

Export As Example

form-control.directive.ts
Usage:

Best Practices

  • Keep directives focused on a single responsibility
  • Use descriptive selector names with prefixes (e.g., appHighlight)
  • Prefer host metadata over @HostBinding and @HostListener decorators
  • Clean up subscriptions in ngOnDestroy
  • Use structural directives to conditionally add/remove DOM elements
  • Use attribute directives to change appearance or behavior
  • Leverage directive composition with hostDirectives to reuse functionality

See Also

Directives Guide

Learn directive fundamentals

Attribute Directives

Create attribute directives

Structural Directives

Build structural directives

Directive Composition

Compose directive behaviors