Reputation: 696
I just started using Angular 2 and was wondering why some properties like selector
and template
are put in components decorators and not in components classes.
What's the point of using all these decorators in Angular 2?
Upvotes: 12
Views: 4268
Reputation: 21
Decorator marks a class as an Angular component and provides configuration which determines how the component should be processed, instantiated, and used at runtime. It provides various options to configure it such as selector, templateUrl, template, styleUrls, styles, providers etc.
Upvotes: 0
Reputation: 31
In angular, we create classes for everything like components, services, directives,
So, how does angular compiler compiles your code and transform it into scripts that are ready to be run in a browser? This happens because of decorators. In simple words, you can say decorators allow you to attach metadata with the typescript class using which angular knows whether that class is a component or directive or module or etc.
Upvotes: 0
Reputation: 657118
To make it easy for tools to provide all kinds of support in templates like:
To generate code from decorators which allows:
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).
Upvotes: 5
Reputation: 16718
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
)
Upvotes: 5
Reputation: 202148
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).
Upvotes: 1