04 08
Angular 2 applications’s basic building blocks
0
Blog

Angular 2 applications’s basic building blocks

Angular is a framework for building client applications in HTML and either JavaScript or a language like TypeScript that compiles to JavaScript.

The framework consists of several libraries, some of them core and some optional.

You write Angular applications by composing HTML templates with Angularized markup, writing component classes to manage those templates, adding application logic in services, and boxing components and services in modules.

Then you launch the app by bootstrapping the root module. Angular takes over, presenting your application content in a browser and responding to user interactions according to the instructions you’ve provided.

There are basically 8 building blocks of Angular 2. These are:

  1. Modules
  2. Components
  3. Templates
  4. Metadata
  5. Data binding
  6. Directives
  7. Services
  8. Dependency Injection

Let’s go over each one of them one by one.

Modules

Angular apps are modular and Angular has its own modularity system called Angular modules or NgModules.

Every Angular app has at least one Angular module class, the root module, conventionally named AppModule.

While the root module may be the only module in a small application, most apps have many more feature modules, each a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities.

An Angular module, whether a root or feature, is a class with an @NgModule decorator.

In short, Modules are blocks of code that do a certain type of task. A module exports some value in the main code, such as class. The first and the most common module that you will study is the one that exports Component Class.

Here’s a simple root module:

app/app.appmodule.ts (excerpt)

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
  imports:      [ BrowserModule ],
  providers:    [ Logger ],
  declarations: [ AppComponent ],
  exports:      [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Here app.appmodule is a module.

Angular libraries

Angular ships as a collection of JavaScript modules. You can think of them as library modules.

Each Angular library name begins with the @angular prefix.

You install them with the npm package manager and import parts of them with JavaScript importstatements.

@angular/core is the most important library that contains most of the modules that we need.

For example:

import Angular's Component decorator from the @angular/core library like this:

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

You also import Angular modules from Angular libraries using JavaScript import statements:

import { BrowserModule } from '@angular/platform-browser';

In the example of the simple root module above, the application module needs material from within that BrowserModule. To access that material, add it to the @NgModule metadata imports like this.

imports: [ BrowserModule ],

Components

A component controls a patch of screen called a view.

A component is basically a class that is used to show an element on the screen. The components have some properties and by using them we can manipulate how the element should look and behave on the screen. We can create a component, destroy, and update as the user moves in the application. Life Cycle hooks are the modules that we use for this purpose. Like ngOnInit()

A component is a controller class with a template which mainly deals with a view of the application and logic on the page. It is a bit of code that can be used throughout an application. Component knows how to render itself and configure dependency injection. You can associate CSS styles using component inline styles, style urls and template inline styles to a component.

To register component, we use @Component annotation and can be used to break up the application into smaller parts. There will be only one component per DOM element

For example,

export class StudentListComponent implements OnInit {
  students: Student[];
  constructor(private service: StudentService) { }

  ngOnInit() {
    this.students = this.service.getStudents();
  }
}

Templates

You define a component's view with its companion template. A template is a form of HTML that tells Angular how to render the component.

A template looks like regular HTML, except for a few differences.

For example:


 <h2>Student List</h2>
 <p><i>Pick a Student from the list</i></p>
 <ul>
 <li *ngFor="let food of foods" (click)="selectedFood(food)">
 {{food.name}}
 </li>
 </ul>
<food-detail *ngIf="selectedFood" [food]="selectedStudent"></food-detail>

Although this template uses typical HTML elements like <h2> and <p>, it also has some differences. Code like *ngFor, {{Student.name}}, (click), [Student], and <Student-detail> uses Angular's template syntax.

Metadata

Metadata tells Angular how to process a class.

For example:


@Component({
selector: 'food-list',
templateUrl: 'app/food-list.component.html',
directives: [FoodDetailComponent],
providers: [FoodService]
})

To tell Angular that we are using a component with certain metadata, we attach a decorator to it (“@”).

Here @Component will be identified as a component class.

Selector tells Angular to render the HTML that templateURL has at this tag <food-list></food-list>

Directives are other components that this Component will require to render and providers are the services required.

The template, metadata, and component together describe a view.

Data binding

Angular supports data binding, a mechanism for coordinating parts of a template with parts of a component. Add binding markup to the template HTML to tell Angular how to connect both sides.

As the diagram shows, there are four forms of data binding syntax. Each form has a direction — to the DOM, from the DOM, or in both directions.

For Example:

<li>{{student.name}}</li>
<student-detail [student]="selectedStudent"></student-detail>
<li (click)="selectStudent(student)"></li>

  1. The {{student.name}} interpolation display food.name value in li tag.
  2. The [student] property binding passes the selected food value from parent to child component.
  3. The (click) event binding calls the selectedFood function when a user clicks on it.
  4. Two-way data binding is an important fourth way that combines property and event binding by the ngModel directive.

Directives

Angular templates are dynamic. When Angular renders them, it transforms the DOM according to the instructions given by directives.

A directive is a class with a @Directive decorator. A component is a directive-with-a-template; a @Componentdecorator is actually a @Directive decorator extended with template-oriented features.

Two other kinds of directives exist: structural and attribute directives.

They tend to appear within an element tag as attributes do, sometimes by name but more often as the target of an assignment or a binding.

Structural directives alter layout by adding, removing, and replacing elements in DOM.

<li *ngFor="let student of students"></li>
<student-detail *ngIf="selectedStudent"></student-detail>

Attribute directives change the appearance of DOM elements. For example:

<input [(ngModel)]="student.name">

Services

Service is a broad category encompassing any value, function, or feature that your application needs.p>

Almost anything can be a service. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.p>

Examples include:

  1. logging service
  2. data service
  3. message bus
  4. tax calculator
  5. application configuration

There is nothing specifically Angular about services. Angular has no definition of a service. There is no service base class, and no place to register a service.

For example:

export class Logger {
  log(msg: any)   { console.log(msg); }
  error(msg: any) { console.error(msg); }
  warn(msg: any)  { console.warn(msg); }
}

Dependency injection

Dependency injection is a way to supply a new instance of a class with the fully-formed dependencies it requires. Most dependencies are services. Angular uses dependency injection to provide new components with the services they need.

Dependency injection allows one to inject a dependency as a service throughout the web application. To inject a dependency we do not create a service but we have a constructor to request the service. The framework then provides it.

For example:

constructor(private service: StudentService) { }

When Angular creates a component, it first asks an injector for the services that the component requires.

An injector maintains a container of service instances that it has previously created. If a requested service instance is not in the container, the injector makes one and adds it to the container before returning the service to Angular. When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments. This is dependency injection.

What Next?

Angular 2 can be written in TypeScript, Dart, or plain JavaScript. But my recommended way is to use TypeScript as of now because their documentation is well-written. To understand each of the layers separately or dive deeper into this, you can see the official documentation available in all of the three aforementioned languages.

Written By

Ankit Jain

Leave a Reply

Your email address will not be published. Required fields are marked *