Decorators in Angular 2 are used extensively.Decorators are used to attach metadata to program elements such as class and properties.Metadata is used to specify details about program entities.Decorators give special meaning to program elements.Here we will look at some of the most commonly used Decorators in Angular 2.
Decorators are a feature of TypeScript and are implemented as functions.The name of the decorator starts with @ symbol following by brackets and arguments,since decorators are just functions in TypeScipt.Following are the benefits of using decorators in Angular 2:
- Since decorators add information declaratively,so extra information about the program elements can be obtained without execution.
- Appropriate JavaScript Code is generated depending upon the declarative information provided by the decorators.
- Helps separation of concerns,since declarative information is separated from the implementation.
We pass the metadata as JSON object argument to the decorator.This JSON object specifies the properties or metadata of the decorator.To know more about decorators in TypeScript please refer Decorators in TypeScript.
There are four types of program elements on which decorators can be applied.They are class,methods,parameters and method arguments.
Following are some of the commonly used decorators in Angular 2:
@NgModule Specifies that a class is Angular module.
@Component Specifies that a class is Angular class.
@Directive Attaches behaviour to HTML DOM or changes its appearance.
@Injectable Informs Angular that decorated class can be used with dependency injector.
@ViewChild Parent component can access child component by using this decorator.
If we take the example of @Component decorator, then it is used to specify that the decorated class is a component.It is one of the most commonly used decorator in Angular2.Since Angular 2 applications is composed of components so you will be using this directive extensively while developing an Angular 2 application.Actually Angular 2 application is just a tree of components ,which has some hierarchy.
We use Component decorator as:
@Component( selector:'home-comp', templete:'<span> Home </span>' ) export class HomeComponent { }
The Component decorator is a class decorator.Here the selector and template specifies the metadata for the component.
As of now most browsers doesn’t support decorators natively.So the TypeScript code must be transpiled to javascript when using decorators.
Leave a Reply