AngularJS 2.0 building blocks explained

Let’s explain the eight building blocks of any Angular 2 app:

  1. Module
  2. Component
  3. Template
  4. Metadata
  5. Data Binding
  6. Directive
  7. Service
  8. Dependency Injection

Module

Component class is something you’d export from a module.

Component

Components controls Views

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:

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">
  1. The “interpolation” displays the component’s hero.name property value within the
    tags
  2. The [hero] property binding passes the selectedHero from the parent HeroListComponent to the hero property of the child HeroDetailComponent
  3. The (click) event binding calls the Component’s selectHero method when the user clicks on a hero’s name
  4. 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:

  1. Structural: They alter layout by adding, removing, and replacing elements in DOM
  2. Attributes: 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.

comments powered by Disqus