AI Hints
Home›Angular Tutorial›Decorators, import and export and Practice: Typed Books
Angular · Lesson 16 of 120

Decorators

The @ in @Component.

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

Angular code is full of words starting with an at sign. At Component, at Injectable, and more. These are decorators.

  • Words with an @
  • @Component
  • Decorators

What a decorator is

A decorator is a function, written with an at sign, just above a class. It runs when the class is defined, not when you use it. It can add information to the class, or change how it behaves. Angular uses decorators to say, this class is a component.

keyvalue
Written@name above a class
It isa function
Runswhen the class is defined
Angularmarks components and services

A small decorator

Shop is a function that returns a decorator. The decorator receives the class, and some context, like the class name. We decorate two classes with it. Run it. The decorator runs for each class, as soon as it's defined. Only then does our last line run.

main.tstypescript
function shop(name: string) {
  return function (target: Function, context: ClassDecoratorContext) {
    console.log(`${String(context.name)} belongs to ${name}`);
  };
}

@shop("The Bookshop")
class BookList {}

@shop("The Bookshop")
class Basket {}

console.log("Classes are ready");
Output
BookList belongs to The Bookshop
Basket belongs to The Bookshop
Classes are ready
Also uses _mode
ts

@Component is a decorator

At Component takes an object, with settings for this class. The selector, and the template, tell Angular how to show it. And the class below becomes a component. Without the decorator, it would just be a normal class.

book.tstypescript
@Component({
  selector: 'app-book',
  template: `<h2>{{ title }}</h2>`,
})
export class BookComponent {
  title = 'Dune';
}

Summary

Decorators are functions, written with an at sign, that run when a class is defined. At Component turns a class into a component. Next, import, and export.

Key takeaways
  • @decorator
  • Runs at definition
  • @Component({...})
Next up: import and export — code in many files