Attribute directives and building your own

Intermediate · 12 min

`ngClass`/`ngStyle` as attribute directives, and how to write a custom one with host bindings and listeners.

Before thisLegacy structural directives: *ngIf, *ngFor, *ngSwitchEvent binding and template reference variables

procademy · 12 min

Attribute directives and building your own

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by procademyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An attribute directive changes how an existing element looks or behaves — it doesn't add or remove elements from the DOM the way a structural directive does.
  • `@HostBinding` lets a directive set a property on the element it's attached to; `@HostListener` lets it react to events on that element — together they're how a directive touches its host without manual DOM APIs.
  • `ngClass` and `ngStyle` are themselves ordinary attribute directives, built from the same `@HostBinding`/`@HostListener` primitives you'll use to write your own.

Two different jobs, both called “directives”

A structural directive (the last two lessons) decides whether and how many times an element exists at all — it operates on the DOM’s shape. An attribute directive is a different job entirely: the element is already there, and the directive changes something about it — a style, a class, a behavior — without adding or removing anything from the tree. ngClass and ngStyle are the two you’ll meet constantly, and both are built from the same two primitives you’ll use to write your own: @HostBinding and @HostListener.

ngClass and ngStyle: directives, not special syntax

<div [ngClass]="{ active: isSelected, disabled: isDisabled }"></div>
<div [ngStyle]="{ color: textColor, 'font-weight': isBold ? 'bold' : 'normal' }"></div>

Both take an object and apply it to the host element — ngClass toggling classes on or off based on truthy values, ngStyle setting inline style properties directly. For toggling one class or one style property, the [class.x]/ [style.y] dot-bindings from an earlier lesson are the more direct tool; ngClass and ngStyle earn their keep specifically when you’re driving several classes or style properties from one object at once, rather than writing out several individual bindings.

Writing your own: @HostBinding and @HostListener

@Directive({
  selector: '[appHighlight]',
  standalone: true,
})
export class HighlightDirective {
  @HostBinding('style.backgroundColor') backgroundColor = '';

  @HostListener('mouseenter') onMouseEnter() {
    this.backgroundColor = 'yellow';
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.backgroundColor = '';
  }
}

Apply it with <p appHighlight>Hover me</p>, and the paragraph highlights on hover with no manual addEventListener or direct style manipulation anywhere in sight. The two decorators are doing complementary jobs: @HostListener wires a method to an event on the host element — the same relationship (event)=... binding has to a template element, just expressed from inside the directive instead. @HostBinding is the mirror image — it lets the directive set a property on its host, the same way [property]=... binding does from a template, just driven by the directive’s own class fields instead of the component’s.

Notice the directive’s selector: [appHighlight], an attribute selector, not an element selector. That’s the convention for attribute directives specifically — they’re meant to be added onto an existing element (<p appHighlight>), not to introduce a new one of their own.

Why build a custom directive instead of just writing the logic inline

You could write the hover-highlight behavior directly on whatever component uses it — a couple of event bindings, a property, done. The reason to extract it into a directive is the same reason you extract any repeated behavior into its own unit: the moment two different elements, in two different components, need the identical hover-highlight behavior, a directive lets you write it once and apply it anywhere with a single attribute, instead of copying the same two (mouseenter)/(mouseleave) bindings into every template that needs it.

This lesson’s video builds a custom attribute directive from scratch using exactly these two decorators — the linked “deeper” video covers ngClass and ngStyle specifically, which is worth watching once you’ve seen how a directive is built, since it’ll be obvious by then that they’re not special-cased Angular magic, just directives like the one you just wrote.

Check yourself

  1. 01What's the structural difference between an attribute directive and a structural directive like the ones from the last two lessons?

    A structural directive changes the DOM's shape — it adds, removes, or repeats elements (that's what the `<ng-template>` wrapping was for). An attribute directive changes an *existing* element's appearance or behavior without touching whether that element exists at all.

  2. 02Inside a custom directive, how do you make the host element's background color change on mouseenter, without writing `addEventListener` yourself?

    `@HostListener('mouseenter') onMouseEnter() { this.el.nativeElement.style.backgroundColor = 'yellow'; }` or, more idiomatically, pair `@HostListener` with `@HostBinding('style.backgroundColor')` so Angular manages the property binding declaratively instead of touching the native element directly.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark