AngularJS 2.0 building blocks explained
Let’s explain the eight building blocks of any Angular 2 app:
- Module
- Component
- Template
- Metadata
- Data Binding
- Directive
- Service
- Dependency Injection
Module
- Optional feature
- Useful if you are using TypeScript which allows you to use
interface
orclasses
export class AppComponent
is like saying that this class is going to be public- Use relative file paths for importing modules
Component class is something you’d export from a module.
Component
Components controls Views
- Logic to support the view can be inside a class
- Angular creates/destroys components as user moves through UI
Template
A form of HTML that describes how to render the Component. It looks mostly like HTML syntax except if you add Angular keywords in them.
Metadata
Some @Component
configuration options:
selector
: css selector to be applied to that html elementtemplateUrl
: address of the component itselfdirectives
: array of components/directives that this component itself requires to function properlyproviders
: an array of dependency injection providers for services
Data Binding
Following are the four possible ways of data binding:
<div>{{hero.name}}</div>
<hero-detail [hero]="selectedHero"></hero-detail>
<div (click)="selectHero(hero)"></div>
<input [(ngModel)]="hero.name">
- The “interpolation” displays the component’s hero.name property value within the tags
- The
[hero]
property binding passes theselectedHero
from the parentHeroListComponent
to the hero property of the childHeroDetailComponent
- The
(click)
event binding calls the Component’sselectHero
method when the user clicks on a hero’s name - Two way data binding combines property and event binding in a single notation using
ngModel
directive
Directive
Class with directive metadata. Even Components are directives - directive with templates. Two other examples are:
Structural
: They alter layout by adding, removing, and replacing elements in DOMAttributes
: Attribute directives alter the appearance or behavior of an existing element. In templates they look like regular HTML attributes, hence the name
Example:
The ngModel
directive, which implements two-way data binding, is an example of an attribute directive.
<input [(ngModel)]="hero.name">
Other examples: ngSwitch, ngStyle, ngClass
Service
It can be any value, function or feature that works well.
Dependency Injection
A way to supply a new class instance with all the requirements. In TypeScript this can be achieved by providing everything inside the constructor.
An Injector
maintains a list of service instances it has created previously so that it can reuse those if needed. The way it achieves this is by utilizing provider
which is used within each Component
.