What is meaning by @ symbol in typescript --Angular 2

前端 未结 2 1977
粉色の甜心
粉色の甜心 2021-02-02 08:41

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 que

2条回答
  •  悲哀的现实
    2021-02-02 09:21

    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: `

    Static Component

    ` }) class StaticComponent {}

    is equivalent to:

    class DynamicComponent {
    }
    
    const dynamicComponent = Component({
        selector: 'dynamic-component',
        template: `

    Dynamic Component

    ` })(DynamicComponent);

    Hope this helps.

提交回复
热议问题