32

I am using typescript for angular 2 application development.

But when we write code for component or route config or some other place we use "@" symbol.

My question is what this symbol means and why it is required?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Pankaj Badukale
  • 1,991
  • 2
  • 18
  • 32

2 Answers2

41

The @ symbol you are referring to is called decorator.

Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members.

Basically when you are doing @component you are telling compiler that the class is a angular2 component with the metadata passed as an argument.

for eg.

@Component({
  moduleId: module.id,
  selector: 'heroes-app',
  templateUrl: 'heroes.component.html',
  styleUrls: ['heroes.component.css'],  
})
class HeroesComponent{}

this code will tell compiler that class HeroesComponent is supposed to be an angular2 component with metadata passed as arguments and it will create a component class.

Decorator isn’t a magic. It’s just function-calling.

for eg.

@Component({
selector: 'static-component',
template: `<p>Static Component</p>`
})
class StaticComponent {}

is equivalent to:

class DynamicComponent {
}

const dynamicComponent = Component({
    selector: 'dynamic-component',
    template: `<p>Dynamic Component</p>`
})(DynamicComponent);

Hope this helps.

Bhushan Gadekar
  • 13,485
  • 21
  • 82
  • 131
13

This means you are applying a decorator.

With the introduction of Classes in TypeScript and ES6, there now exist certain scenarios that require additional features to support annotating or modifying classes and class members. Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members. Decorators are a stage 1 proposal for JavaScript and are available as an experimental feature of TypeScript.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I have read reference links provided by @Gunter and found as its nothing but just some CODE which get injected in actual CODE at runtime....but to inject it we use name of function preceded with @ symbol so Typescript understand that it is decorator and it should be take care while transpelling or later on. Plz correct me if I am wrong. – Pankaj Badukale Jul 03 '16 at 13:50
  • Decorators can be interpreted statically (without actually running the code) Angular uses this to generate code at build time (offline template compiler) and for tooling support like autocompletion in templates (both work in progress). – Günter Zöchbauer Jul 03 '16 at 14:18
  • Taking advantage of this question... why have they decided to put '@' signs on their npm packages aswell?? import "@angular/core" and etc ... – weisk Jul 03 '16 at 15:12
  • 1
    As far as I know this is an NPM feature and creates a reserved namespace where only the Angular team can publish packages to. – Günter Zöchbauer Jul 03 '16 at 15:15