Wednesday 22 February 2017

Angular 2 Component


Angular 2 application uses the component pattern. It allow us to breakdown the project/product into well defined discrete smaller components. For example smart phone battery is component of a smart phone. In software development we can say that components are logical units that can be combined in a specific way(interfaces) to build large application. Components are basic building block of an angular 2 application. Furthermore we bundle/combine these components through angular module. At high level we can say that to develop angular application you
1. create the component
2. bundle them into module
3. bootstrap your application
Component = Template (View Layout  Angularized HTML) + Class (Data + Behavior)  + Metadata (Defined with angular decorator)
Here is the example code link
In the example code above we will focus only on app.component.ts
Class:
Right now for simplicity it only has one property as “name”.
1
2
3
4
5
6
export class AppComponent {
name:string;
constructor() {
this.name = 'Angular2 Component'
}
}
Metadata and angularized html tempalate:
In this example we are using inline HTML Template with interpolation binding feature of Angular 2 {{name}}
1
2
3
4
5
6
7
8
@Component({
selector: 'my-app',
template: `
<div>
<h2>This is my first {{name}}</h2>
</div>
`,
})
Decorator is function that adds metadata to class, its members or its methods arguments
Decorator start with @ sign.
Angular do provide built in decorators.
@Component is angular 2 built in decorator that takes an object as parameters. You can say angular 2 decorator are similar to C# class attribute. Also notice that there is no comma after @Component({})
Import:
1
import {Component} from '@angular/core';

We import what we need using import statment.

Hope it help to understand angular 2 component.