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

Directives

Add behaviour to elements.

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

Pipes change how values look. Directives change how elements look, and behave. In fact, every component is a directive, with its own template.

  • Pipes change values
  • Directives change elements
  • Components are directives

Kinds of directives

Components are directives with a template. Attribute directives change an element that already exists, like its classes, or styles. Structural directives used to add, and remove elements, but at if, and at for, now do that job.

KindWhat it does
Componenta directive with a template
Attribute directivechanges an existing element
Structural (old)*ngIf, *ngFor, now @if, @for

A built-in directive

Ng class takes an object. Each key is a class name, and each value decides whether it's added. Run it. The Hobbit is crossed out, and red, because both conditions are true. Circe, and Persuasion, are red, because stock is low.

app.tstypescript
import { Component } from '@angular/core';
import { NgClass } from '@angular/common';
import { BOOKS } from './books';

@Component({
  selector: 'app-root',
  imports: [NgClass],
  template: `
    @for (b of books; track b.id) {
      <p [ngClass]="{ 'sold-out': b.stock === 0, low: b.stock < 3 }">{{ b.title }}</p>
    }
  `,
  styles: `.sold-out { text-decoration: line-through; } .low { color: crimson; }`,
})
export class App {
  books = BOOKS;
}
Also uses books.ts
export interface Book {
  id: number;
  title: string;
  author: string;
  price: number;
  stock: number;
}

export const BOOKS: Book[] = [
  { id: 1, title: 'Dune', author: 'Frank Herbert', price: 9.99, stock: 4 },
  { id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien', price: 8.99, stock: 0 },
  { id: 3, title: 'Circe', author: 'Madeline Miller', price: 10.99, stock: 2 },
  { id: 4, title: 'Emma', author: 'Jane Austen', price: 6.99, stock: 7 },
  { id: 5, title: 'Persuasion', author: 'Jane Austen', price: 7.49, stock: 1 },
];

ngClass or class bindings?

Ng class is handy for several classes at once. But for new code, Angular recommends plain class bindings. They need no import, and they're a little faster.

[ngClass]

  • an object of classesneeds an importolder style

[class.name]

  • one class eachno importrecommended

Summary

Directives change elements. Components have templates, and attribute directives change existing elements. Next, writing our own attribute directive.

Key takeaways
  • Components
  • Attribute directives
  • @if replaces *ngIf
Next up: Custom Attribute Directives — your own directive