问题
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?
回答1:
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
upcomingoffline 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).
回答2:
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
)
回答3:
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:
- https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7#.ryvc6ewsc
You can notice that decorators can apply in TypeScript at different levels (class, class property, method parameter).
回答4:
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.
来源:https://stackoverflow.com/questions/38069790/why-does-angular-2-use-decorators