Why does Angular 2 use decorators? Why does Angular 2 use decorators? angular angular

Why does Angular 2 use decorators?


  • To make it easy for tools to provide all kinds of support in templates like:

    • error checking
    • auto-completion
    • graphical GUI designers
  • To generate code from decorators which allows:

    • to define some things more declaratively or
    • generate different code depending on some configuration (like the upcoming offline template compiler does)

Code would need to be executed to use results expressions might emit. Decorators can be easily evaluated statically without executing the TypeScript code (except maybe a simple and limited subset).


In addition to the platform-specific answers already there, I'd love to chip in from a more generic view. This question, from my opinion, is somehow related to the decision of choosing decorator pattern over inheritance (e.g. @Component vs extends Component)

Some of the benefits of using decorators are:

1. Separation of concerns:

Information inside decorators is declarative, they define the behaviour of a class, most likely won't change over time and are used by the framework. Class properties and fields are class-specific data, will always be processed and frequently updated, and only are meaningful within the class itself. These two kinds of data should not be mixed together.

2. Support multiple modifications

Many languages prevent multiple inheritance due to Diamond problem. On the other hands, one class can have multiple decorators for different purposes (e.g. @Component and the deprecated @RouteConfig)


In general, decorators allow you to execute functions. For example @Component executes the Component function imported from Angular2. Under the hood, such decorators define some metadata on the class. This allows you to configure the class to "flag" it as a component. Angular2 is then able to link selectors in templates to such class.

This article could give you more hints about what happens under the hood:

You can notice that decorators can apply in TypeScript at different levels (class, class property, method parameter).