Loading ...

What Is Angularjs 2 Component

Introduction

Here I want to write of how I grasped what is Angular 2 component building blocks

 

Hello everybody,

I don't know about you, but when I first opened AngularJS 2 component source code, I've become puzzled with question mark of what is AngularJS 2 component?

Imagine, that you look at this sampe:

import { Component } from '@angular/core';

@Component({
       selector: 'my-app',
       template: `<h1>Hello {{name}}</h1>`
})
export class AppComponent { name = 'Angular'; } 

 

and try to figure out what are consisting parts of compoment? After watching on that example and some others example here is conclusion that I've made:

Angularjs 2 Component.png

Do you remember previous fragment of code? Take a look with explanation of those hexagons:

Angularjs 2 Component in source code.png

hope this hexagons along with green rectangles will make your understanding of what makes AngularJS 2 component easier.

Now let's go deeper in this fragment of text:

export class AppComponent { name = 'Angular'; } 

Or even we will fromat it a bit better to make understanding deeper:

export class AppComponent {

         name: string = 'Angular';

} 

AppComponent explanation.png

Next goes understanding of what is metadata or this part of code:

 

@Component({
       selector: 'my-app',
       template: `<h1>Hello {{name}}</h1>`
})

Before continuing with another drawings, following  understanding will be needed: Decorator. In other words, decorator is function that adds metadata to something. That something can be class, members, method arguments. Few other features of decorators:

  • prefixed with @
  • Angular provides built-in decorator which is named @Component
  • decorater is applied to something, before it is described
  • if you are from C# world ( as I am ) you can compare decorator with attributes

Take look at it on the screen with rectangles as well:

Angularjs 2 Metadata.png

Few other words related to that description.

selector property says to AngularJS 2: please define for me selector 'my-app'

component also defines template. The one which is described. 

And {{name}} indicates data binding. It means that field name will get value name from the class AppComponent.

I hope this explanations will help to make understanding of AngularJS 2 components little bit more structured for somebody