Why do Angular 2 use decorators?

I just started using Angular 2 and wondered why some properties, such as selector and template , are placed in component decorators, and not in component classes.

What is the point of using all these decorators in Angular 2?

+10
decorator angular angular-decorator
source share
4 answers
  • To simplify tools to support all types of support in templates, for example:

    • error checking
    • autofill
    • GUI graphic designers
  • Generate code from decorators, which allows you to:

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

Code must be executed to use result expressions. Decorators can be easily evaluated statically without executing TypeScript code (with the possible exception of a simple and limited subset).

+3
source share

In addition to the answers already received on a specific platform, I would like to add a more general view. This question, in my opinion, is somehow related to the decision to choose a decorator template instead of inheritance (for example, @Component vs extends Component )

Some of the benefits of using decorators are:

1. Separation of interests:

The information inside decorators is declarative, it determines the behavior of the class, most likely it will not change over time and is used by the platform. The properties and fields of the class are class-specific data, will always be processed and often updated, and only make sense inside the class itself. These two types of data should not be mixed together.

2. Support for multiple modifications

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

+5
source share

In general, decorators allow you to perform functions. For example, @Component performs a Component function imported from Angular2. Under the hood, such decorators define some metadata in the class. This allows you to configure the class for the "flag" of it as a component. Angular2 can then bind selectors in templates to such a class.

In this article, you can learn more about what is happening under the hood:

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

0
source share

In angular, we create classes for everything, for example, for components, services, directives,

So, how does the angular compiler compile your code and turn it into scripts that are ready to run in a browser? This is due to decorators. Simply put, you can say that decorators allow you to attach metadata to a typing class, using which angular knows if this class is a component, directive, module, etc.

0
source share

All Articles