Sub topic 1
What attribute directives are and when to use them
Prerequisites
This chapter assumes you already know:
- TypeScript basics, including classes and decorators.
- Angular components and templates.
- Standalone components and the
importsarray. - Basic template syntax: property binding with
[prop]and event binding with(event).
You do not need to have written a directive before. This chapter explains what attribute directives are and when to choose one. Later chapters cover the full API.
What a directive is
A directive is a class that Angular attaches to an element in a template. Angular creates an instance of the class for each matching element and gives it access to that element. The element is called the host element, or simply the host.
Angular has three kinds of directives:
- Components
- Structural directives
- Attribute directives
All three are classes that Angular matches against elements by a selector. They differ in what they are allowed and expected to do.
The three kinds compared
| Kind | Has its own template | Typical job | Example |
|---|---|---|---|
| Component | Yes | Renders a piece of UI | `<app-card>` |
| Structural directive | No | Adds, removes, or repeats parts of the DOM | custom `*appUnless` |
| Attribute directive | No | Changes the look or behavior of an existing element | `appHighlight`, `ngModel` |
Components
A component is a directive with a template. It is declared with @Component, and an element can host at most one component. If you need to draw new content, you want a component.
Structural directives
A structural directive changes the shape of the DOM. It decides whether a piece of template exists at all, or how many copies of it exist. Custom structural directives work with TemplateRef and ViewContainerRef and are written with the * prefix. Angular's own *ngIf and *ngFor have been replaced in new code by the built-in @if and @for control flow blocks, but the structural directive mechanism still exists for your own use.
Attribute directives
An attribute directive leaves the element in place and changes how it looks or acts. It can:
- Set styles, classes, or attributes on the host.
- Listen for events on the host and react to them.
- Add behavior such as focus handling, tooltips, or click tracking.
The name comes from how you write it. It looks like an attribute on an element, as in <p appHighlight>. The built-in NgClass, NgStyle, and NgModel directives are attribute directives.
Attribute directives can also be applied to a component's host element, not only to plain HTML elements. For example, you can put appHighlight on <app-card>. The directive then acts on the <app-card> element, which is the component's host.
A first look
The smallest useful attribute directive looks like this.
import { Directive, ElementRef, inject } from '@angular/core';
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
constructor() {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}Three parts matter here:
@Directivemarks the class as a directive. It has no template.- The selector
[appHighlight]is a CSS attribute selector. The directive matches any element that has anappHighlightattribute. inject(ElementRef)gives the directive a reference to its host element. Angular creates one instance of the class per matching element, so each instance holds its own host.
A standalone component applies the directive by listing it in imports and using the attribute.
import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';
@Component({
selector: 'app-demo',
imports: [HighlightDirective],
template: `<p appHighlight>This paragraph is highlighted.</p>`,
})
export class DemoComponent {}If you leave HighlightDirective out of imports, Angular does not report an error for a plain attribute like appHighlight. The attribute is treated as ordinary markup and nothing happens. This silent failure is a common first mistake, and you should check imports first when a directive seems to do nothing.
The ElementRef code above is only a preview. Later chapters cover safer ways to change the host. This chapter is about deciding when a directive is the right tool.
Why attribute directives exist
You can already change an element from a component. You can bind to [style.color], [class.active], or (click) in any template. A directive is worth writing when the same element-level behavior is needed in many places.
Consider a rule such as "when the mouse is over this element, show a gray background". Without a directive, you repeat the same bindings on every element:
- A boolean field to track hover state.
- Two event bindings to flip it.
- A style binding that reads it.
That code is noisy and drifts out of sync as copies are edited. A directive moves the logic into one class. Each use is a single attribute.
A directive also keeps the behavior separate from the content. The element's owner decides what the element is, and the directive adds what it does. That separation works across different host types. The same directive can sit on a <p>, a <button>, or a component.
Several directives can sit on one element at the same time. An element can have a tooltip directive, a click-tracking directive, and a highlight directive, and they do not conflict as long as they do not fight over the same property. Only one component can be on an element, so this stacking is something only directives provide.
Choosing the right tool
The decision depends on what you need to change. The diagram follows the questions in order.
Use the following criteria in practice.
Choose an attribute directive when
- The behavior applies to an element that already exists and needs no template of its own.
- The same behavior is used on several different elements or components.
- The behavior needs the element itself, such as focus, size, scroll position, or event listeners that you want cleaned up automatically.
- You want to combine several small behaviors on one element.
Typical examples are auto-focus on load, click-outside detection, a tooltip trigger, drag handles, permission-based disabling, and input masks.
Do not choose an attribute directive when
- A single
[class.x]or[style.x]binding does the job on one element. A directive adds a file and an indirection for no gain. - You need to render new markup. That is a component.
- You need to show or hide a block of template. Use
@if, or a structural directive if you need reusable logic. - You only need to transform a value for display. A pipe is the right tool because it works on values, not elements.
- The logic does not touch an element at all, such as fetching data or sharing state. Use a service.
How a directive differs from a component in practice
A component and an attribute directive share most of their decorator options, including selector, inputs, outputs, and host. The practical differences are:
- A directive has no
template,templateUrl,styles, orimports. It cannot render anything. - Component selectors are usually element names such as
app-card. Directive selectors are usually attributes in brackets, such as[appHighlight]. - An element has at most one component but any number of directives.
- A component creates its own view and, by default, Angular's style scoping for it. A directive creates neither. The host's styles belong to the component whose template contains the host.
A directive's selector is not limited to a bare attribute. A selector such as button[appConfirm] restricts the directive to <button> elements that have the attribute. This is useful when the directive only makes sense on one element type, because Angular will not match it anywhere else.
Naming conventions
Angular's style guide recommends a short prefix for your directive selectors. Examples in this tutorial use app, as in appHighlight. A prefix has two purposes:
- It avoids collisions with native HTML attributes and with attributes from third-party libraries.
- It makes it clear in a template which attributes are Angular directives.
Selectors are written in lowerCamelCase for attributes, such as appHighlight. The class name then uses the same name in UpperCamelCase and ends with Directive, as in HighlightDirective.
Where this chapter fits
The next chapters build on this decision step by step:
- Declaring the directive and its attribute selector in detail.
- Applying it from a standalone component.
- Changing the host safely with
Renderer2and host bindings. - Handling events and accepting inputs and outputs.
- Injecting services, composing with
hostDirectives, and testing.
Before moving on, keep in mind the one idea that ties them together. An attribute directive is code attached to an existing element, so everything it does is about that host element.
Exercise
You have a settings page with three <input> elements. You want each of them to select all of its text when the user focuses it, and you expect to need this on many other pages. Which of these should you use: a component, a structural directive, an attribute directive, or a plain event binding? Give your reason.
Show answer
An attribute directive. The behavior acts on elements that already exist and needs no template, so a component is wrong. No part of the DOM is added or removed, so a structural directive is wrong. A plain (focus) binding would work on one input, but you would have to repeat it on every input and every page. A directive with the selector [appSelectOnFocus] keeps that logic in one class and costs one attribute per use.
Exercise
A teammate wrote <p appHighlight>Hello</p> in a standalone component, and the paragraph is not highlighted. The directive class has the correct @Directive decorator and selector [appHighlight]. What is the first thing you check, and why does Angular not report an error?
Show answer
Check that HighlightDirective is listed in the component's imports array. Without it, Angular does not match the directive to the element. Because appHighlight is a valid HTML attribute name, Angular treats it as ordinary markup and does not raise an error.