Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Angular 2 use decorators?

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?

like image 378
Neo Avatar asked Jun 28 '16 07:06

Neo


People also ask

Why do we need decorators in Angular?

The whole purpose of Angular decorators is to store metadata about a class, method, or property. When you configure a component, you are providing a metadata for that class that tells Angular that you have a component, and that component has a specific configuration.

Why do we need decorators in TypeScript?

Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members. Decorators are a stage 2 proposal for JavaScript and are available as an experimental feature of TypeScript. NOTE Decorators are an experimental feature that may change in future releases.

What's the difference between annotations and decorators in Angular 2?

Annotations are only metadata set on the class using the Reflect Metadata library. Decorator corresponds to a function that is called on the class. Annotations are used for creating an attribute annotations that stores array. Decorator is a function that gets the object that needs to be decorated.

What is meant by decorators in Angular?

Decorators are design patterns used to isolate the modification or decoration of a class without modifying the source code. In AngularJS, decorators are functions that allow a service, directive, or filter to be modified before it is used.


1 Answers

  • 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).

like image 91
Günter Zöchbauer Avatar answered Oct 04 '22 22:10

Günter Zöchbauer