AI Hints
Home›Angular Tutorial›Custom Pipes, Directives and Custom Attribute Directives
Angular · Lesson 60 of 120

Custom Attribute Directives

Your own directive.

⏱ 2 min read▶ Video at 1:10:40🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Let's write a directive that highlights any element. Add one attribute, and the background changes colour.

  • Highlight anything
  • One attribute
  • Your own directive

Writing a directive

A directive is a class, with the directive decorator. Its selector is an attribute name, in square brackets. Host bindings change the element it's placed on. And inputs let the attribute carry a value.

keyvalue
@Directive({ ... })the decorator
selector: '[appHighlight]'an attribute
host: { ... }change the element
input()the attribute's value

highlight.ts

The selector is in square brackets, so it matches an attribute. Host binds the element's background colour. The input has the same name as the attribute, so the attribute's value becomes the colour. With no value, it falls back to yellow.

highlight.tstypescript
import { Directive, input } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  host: { '[style.background-color]': 'appHighlight() || "yellow"' },
})
export class Highlight {
  appHighlight = input('');
}

Highlighting paragraphs

The paragraphs use the directive as an attribute. The first has no value, and the second asks for light blue. The third doesn't use it. Run it. The directive coloured two plain paragraphs, without changing their tags.

app.tstypescript
import { Component } from '@angular/core';
import { Highlight } from './highlight';

@Component({
  selector: 'app-root',
  imports: [Highlight],
  template: `
    <p appHighlight>Dune is back in stock.</p>
    <p appHighlight="lightblue">Circe is our book of the month.</p>
    <p>Emma is a normal paragraph.</p>
  `,
})
export class App {}
Also uses highlight.ts
import { Directive, input } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  host: { '[style.background-color]': 'appHighlight() || "yellow"' },
})
export class Highlight {
  appHighlight = input('');
}

Summary

An attribute directive has an attribute selector, host bindings to change the element, and inputs for its value. Next, reacting to events with host listeners.

Key takeaways
  • selector: '[appHighlight]'
  • host: { ... }
  • input()
Next up: host Listeners — react to events