Angular is a framework for a client application. It is not a library like Jquery.
Angular application consist of following main building blocks:
- Modules
- Components
- Templates
- Metadata
- Data binding
- Directives
- Services
- Dependency Injection
Let's go through each of these in detail
Modules:
- Angular has its own modularity called angular modules or NgModules
- The angular module is a class adorned with a @NgModule function which takes metadata object to tell the compiler how to compile and run the module.
- Every application has at least one module [Root module] that you bootstrap to launch the application. the conventional name for this root module is AppModule [you can call it anything you want]. the sample AppModule code is given below:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { FormsComponent } from './forms.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In the above snippet, NgModule Identifies AppModule as an angular module. NgModule is a decorator function that takes single metadata object whose properties are:
- declarations: It is an array. you must declare every component in one NgModule class. by listing the components here, you are telling the angular which component belongs to the AppModule.
Note: only Components, directives or pipes goes into declaretions. Not NgModule classes[built in NgModule classes]
- exports: This is a subset of declarations which should be visible and usable in the component's template of other modules.
- imports: Many features of angular are designed as angular modules. for example, Http services are in HttpModule, the router in RouterModule. We add modules to import array when the application requires its features.
Note: Only NGModule classes go in the imports. Dont put othere kind of classes here.
- providers: Services specified here become accessible in all parts of the app.
- bootstrap: Here you mention the component that you bootstrap to launch the application. The bootstrap process creates components listed and inserts each into browser DOM. Most of the application have only one component tree and they bootstrap single root component but you can put more than one component tree on a host web page. Bootstrapping sets up the executable environment, digs root AppComponent out of module's bootstrap array and created an instance of the component and insert it within element tag identified by component's selector. recommended place for bootstrap is app/main.ts.
Components:
- Components are the main building blocks of angular 2. It controls view.
- Angular creates, updates and destroys components as a user moves through the application. Your application can take action at each moment in this life cycle. Sample component code:
import { Component } from '@angular/core';
@Component({
selector: 'author',
templateUrl: './author.component.html',
styleUrls: ['./author.component.css'],
providers:[AuthorService]
})
export class AuthorComponent
{
title = 'Authors';
authors;
showAuthors: boolean;
constructor(authorService:AuthorService) {
this.showAuthors=false;
this.authors=authorService.getAuthors();
}
toggleshowAuthors()
{
if(this.showAuthors)
this.showAuthors=false;
else
this.showAuthors=true;
}
addAuthor(author)
{
this.authors.push(author);
}
deleteAuthor(index)
{
this.authors.splice(index,1);
}
}
- Above code is the sample AuthorComponent [I have implemented some methods in the component, which will be used later in this article to explain data binding and services]. As you can see in the above code export keyword is used before class, This export indicates that I am exporting AuthorComponent class so that it is available to other modules in the app. Later when I need this, I can import it.
- To make this class as a component, angular makes use of @component annotation. For this, we need to import component decorator from Angular core [first statement in the snippet].
- The @component decorator takes metadata object. we will in details about it in next section.
- Once we create a component with selector 'author', How to make use of this component? The answer is we need to add <author> element somewhere in the template of other components.
- When we use the component selector in other component's template, we need to specify the directives to let the angular know which component the <author> refers to.
Template:
- Template is a companion of the component, used to define component's view. Sample template:
<h1{{title}}</h1>
<button (click)="toggleshowAuthors()">
{{showAuthors ? "Hide Authors" : "Show Authors"}}
</button>
<div *ngIf="showAuthors">
<ul>
<li *ngFor="let author of authors; let i = index">
{{author}}
<button (click)="deleteAuthor(i)">X</button>
</li>
</ul>
</div>
<form (submit)="addAuthor(author.value)">
<input type="text" #author />
</form>
<courses></courses>
- Template uses typical HTML plus angular's template syntax such as ngFor, (click), {{title}}
- In the last line of the template, the <courses> tag is a custom element that represents a new component, CoursesComponent.
- the template of a component can be specified inline to a component or you can specify the view in the separate HTML file and give the link of the file to templateUrl of the component as shown below.
templateUrl: './author.component.html',
Metadata:
- Metadata tells angular how to process a class. To tell angular particular class is a component, attach metadata to the class. this metadata is attached to a class using decorator[@component discussed earlier].
- Let's understand the properties of the metadata and its significance.
selector: CSS selector that tells Angular to create and insert an instance of this component where it finds a <author> tag in parent HTML. Angular inserts an instance of the AuthorComponent view between <author> tags.
template: Component's view is defined here in line to the component. You can also define the view in a separate Html file and give the Url in the templateUrl attribute.
providers: It is an array of dependencies (Services) that component requires. If the component is using the functionality of service, that service needs to be imported and provided in this list.
Ex: providers :[Logger]
The above example is shorthand expression for provider registration using provider object literals with 2 properties =>
You can also provide ready-made object rather than asking the injector to create it from the class. EX:
let logs ={logs:["Log message"],lao : ()=>{}};
[{provider:Logger, useValue:logs}]
Data Binding:
- Without the framework, the developer would be responsible for pushing data into HTML controls and turning user responses into actions and perform updates. Writing all these logic is tedious and error prone.
- Angular supports data binding which helps to display data in UI using different types of data binding.
- Interpolation: It is an easier way to display component's properties. To display component's property value in view, bind property name with interpolation {{}}. Ex: {{title}}
- Property binding: Property binding passes the value of 'selectedAuthor' from the parent component to the author property of AuthorDetailsComponent. Binds value of one property to other.
<author-detail [author]="selectedAuthor"></author-detail>
3. Event Binding:
<li (click)="selectAuthor(author)">{{author.name}}</li>
Event binding calls the selectAuthor() method when the user clicks on author name.
4. Two-way binding: It is an important type which combines property and event binding in single notation using ngModel directive. Ex:
<input [(ngModel)]="author.name">
The punctuation in the syntax [()] is a good clue to understand what's going on here. We can break ngModel into 2 separate modes.
[] => In property binding, value flows the model to target property. we identify that by surrounding target by []. this is one way binding from model to the view.
() => In event binding, value flows from target property to the model. We identify that by (). this is another way of binding from view to model.
Directives:
- A component is a directive with a template. While a component is technically a directive, components are so distinctive and central to Angular applications that this architectural overview separates components from directives.
- Directives are adorned with @Directive. There are 2 kinds of directives:
- Attribute directive: This tends to appear within the element as attributes do, sometimes by name but more often as a target of an assignment or binding. Attribute directives alter the appearance or behavior of an existing element. The ngModel directive, which implements two-way data binding, is an example of an attribute directive.
- Structural directive: This directive alters layout by adding, removing, and replacing elements in DOM. Ex: the following code uses 2 built-in structural directives.
<li *ngFor="let author of authors"></li>
<hero-detail *ngIf="selectedAuthor"></hero-detail>
- *ngFor tells Angular to place out one <li> per author in the authors list.
- *ngIf includes the AuthorDetail component only if a selected author exists.
you can also write your own directives. For example find below the code for directive autoGrow, which increases the width of the input element on focus.
import {Directive, ElementRef, Renderer} from '@angular/core';
@Directive({
selector: '[autoGrow]',
host: {
'(focus)': 'onFocus()',
'(blur)': 'onBlur()'
}
})
export class AutoGrowDirective {
constructor(private el: ElementRef, private renderer: Renderer)
{
}
onFocus() {
this.renderer.setElementStyle(this.el.nativeElement, 'width', '200px');
}
onBlur() {
this.renderer.setElementStyle(this.el.nativeElement, 'width', '120px');
}
}
<input type="text" autoGrow name="title" />
Services:
- Services encompass any values, functions or features that your application needs. Service is typically a class with a well-defined purpose.
- There is nothing angular about services. Angular has no definition for a service. There is no service base class, and no place register a service.
- The component class should be lean. they don't fetch data from the server, validate input, or log directly to the console. they delegate such tasks to the service class. Component's job is to enable the user experience. It mediates view and application logic [services]. Angular does not enforce these principles.
- Sample service code is:
import { Injectable } from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthorService {
constructor(private http:Http) { }
getAuthors():string[]
{
return ['author1', 'author2', 'author3', 'author4'];
}
getPosts()
{
return this.http.get('http://jsonplaceholder.typicode.com/posts').map(res => res.json());
}
}
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthorService {
constructor(private http:Http) { }
getAuthors():string[]
{
return ['author1', 'author2', 'author3', 'author4'];
}
getPosts()
{
return this.http.get('http://jsonplaceholder.typicode.com/posts').map(res => res.json());
}
}
Dependency Injection[DI]:
- Angular uses DI to provide new components with the services they need. Angular can tell which service the component needs by looking at constructor's argument.
constructor(authorService:AuthorService) { }
- Injector maintains a container of service instances that it has previously created. If the requested service is not found in the container, it creates one and adds it to the container before returning it to the angular. when all the requested services have been resolved, angular calls the component's constructor with these services. This is DI.
- You need to import and specify the dependent services in providers list of the component. Ex:
import {AuthorService} from './author.service';
@Component({
selector: 'author',
templateUrl: './author.component.html',
styleUrls: ['./author.component.css'],
providers:[AuthorService]
})
- You can register providers in the module or in the component. If you add providers to a component, then you will get a new instance of service with each new instance of the component. If you add to root module, the same instance of service will be available everywhere.
That's a foundation for everything else in an Angular application, and it's more than enough to get going. But it doesn't include everything you need to know.

