Angular 2 Annotations

We have already used annotations in our hello world example.

Annotations are not specific to Angular 2. We use them in other programming languages.

Annotations add some metadata to our class. Why metadata? Simply it gives a meaning to our class.

 

Try it Yourself , see the @ annotation in action.

live example at the end of the article

try it angular 2 annotations
try it angular 2 annotations

Another synonym of Annotations is Decorator.

Decorator: is a function that adds Metadata to a class. Decorators are part of JavaScript. Implemented in Typescript and they are standardized by the ES2016.

angular 2 annotations decorators
angular 2 annotations decorators

Let’s talk about Angular 2 Annotations:

@Component is an annotation that tells Angular 2 that the attached class is a component.

@Component describes details about the Component (selector, template, styles…)


/**
* Created by Tareq Boulakjar. from angulartypescript.com
*/
import {Component} from 'angular2/core';

@Component({
selector: 'hello-world',
template:'<h3>Angular 2 Hello World</h3>'
,
})

export class Angular2AnnotationsComponent { }
/*
Copyright 2016 angulartypescript.com. All Rights Reserved.
Everyone can use this source code; don’t forget to indicate the source please:
http://www.angulartypescript.com/
*/

  • We can keep only the selectorhello-world’. In this case we tell Angular 2 that we want to create a tag with the name <hello-world></hello-world> but it doesn’t have a template.
  • The selector is actually the CSS selector.

 

from where those annotations come from
from where those annotations come from

 

Those annotations come from angular 2  core library in

import {Component} from ‘angular2/core‘;

angular 2 annotations