Sarvesh Yadav
Sarvesh Yadav

Reputation: 2620

What is the difference between annotation and decorator?

I am confused when to use term annotation and when to use decorator ?

 @Component({
      selector: 'tabs',
      template: `
      `
    })
    export class Tabs {

    }

Upvotes: 27

Views: 34780

Answers (3)

Ali Adravi
Ali Adravi

Reputation: 22723

Code from a component:

@Component({
  selector: 'app-customer-detail',
  ......
})

@Component: is a decorator

app-customer-detail: is an annotation

Decorators provide a way to add both annotations and 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.

There are different types of decorators:

  • Class Decorator : @Component
  • Method Decorator: @HostListener
  • Property Decorator: @Input/@Output
  • Parameter Decorator: @Inject

Upvotes: 2

Pardeep Jain
Pardeep Jain

Reputation: 86730

Traceur gives us annotations. TypeScript gives us decorators. But Angular 2 supports both.

Annotations create an "annotations" array. whereas Decorators are functions that receive the decorated object and can make any changes to it they like.

As angular use TypeScript instead of atScript so it is using decorators. There are basically four kind of decorators are there which are

  • Class decorators, e.g. @Component and @NgModule
  • Property decorators for properties inside classes, e.g. @Input and @Output
  • Method decorators for methods inside classes, e.g. @HostListener
  • Parameter decorators for parameters inside class constructors, e.g. @Inject

For more in depth you can refer

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202146

A decorator corresponds to a function that is called on the class whereas annotations are "only" metadata set on the class using the Reflect Metadata library.

With TypeScript and ES7, @Something is a decorator. In the context of Angular2, decorators like @Component, @Injectable, ... define metadata for the decorated element using the Reflect.defineMetadata method.

This question could interest you to find out what a decorator actually is:

Upvotes: 24

Related Questions