A Comprehensive Guide To Angular 4

Zulaikha Geer
Edureka
Published in
16 min readMay 30, 2017
Angular Tutorial — Edureka

Before going through this Angular Tutorial article, I would like to draw your attention a bit. You must have gone through many web & mobile applications which are responsive & dynamic. It does not reload the whole page and instead reloads only the required section. For example Gmail, you might have noticed that when you click on an email, it only reloads that e-mail in the body section and does not retrieve the rest of the page like side and navigation bar. These kind of applications are SPA (Single Page Application) and are developed using Angular. Some of the most popular examples are Netflix, PayPal, freelancer etc.

In this article, we will discuss the evolution of Angular and then moving on, we will understand the building blocks of Angular. We will be talking about Angular instead of Angular 2 or Angular 4 as from Angular 2 on-wards Angular community has decided to refer any version of Angular as just Angular. In this Angular Tutorial article, we will be covering:

  • Evolution of Angular
  • Differences between AngularJS and Angular
  • Angular Features
  • Building Blocks of Angular
  • Modules
  • Components
  • Templates
  • Metadata
  • Data Binding
  • Directives
  • Services
  • Dependency Injection

Let us move ahead and try to understand the evolution of Angular.

Evolution of Angular

Angular is a JavaScript-based open-source framework for building client-side web applications. So, let us first understand Javascript. JavaScript runs on the client side of the web, which can be used to design or program how the web pages behave on the occurrence of an event. Typically, JavaScript is used for interface interactions, slideshows, and other interactive components. JavaScript evolved quickly and has also been used for server-side programming (like in Node.js), game development, etc.

JavaScript deals with dynamic content, which is an important aspect of web development. Dynamic content refers to constantly changing content and it adapts to specific users. For example, JavaScript can be used to determine whether or not to render the mobile version of the website by checking the device, which is accessing the website.

This encouraged web developers to start creating their own custom JavaScript libraries for reducing the number of code lines and implementing complex functionalities easily. jQuery is a fast, small, and feature-rich JavaScript library, which makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API. jQuery became the most popular one because it was easy to use and extremely powerful.

Since jQuery has no real structure, the developer has full freedom to build projects as they see fit. However, the lack of structure also means it’s easier to fall into the trap of “spaghetti code,” which can lead to confusion in larger projects with no clear design direction or code maintainability. For these situations, a framework like Angular can be a big help.

Angular is a client-side JavaScript framework that was specifically designed to help developers build SPAs (Single Page Applications) in accordance with best practices for web development. By providing a structured environment for building SPAs, the risk of producing “spaghetti code” is highly reduced. So, you must be wondering what is SPA?

Single-page application (or SPA) are applications that are accessed via a web browser like other websites but offer more dynamic interactions resembling native mobile and desktop apps. The most notable difference between a regular website and SPA is the reduced amount of page refreshes. SPAs have a heavier usage of AJAX- a way to communicate with back-end servers without doing a full page refresh to get data loaded into our application. As a result, the process of rendering pages happens mostly on the client-side.

For example, if you go through Gmail, you will notice that while opening mail from the inbox will only fetch the email and display it in place of the e-mail list. The rest of the components like sidebar, navigation bar etc. are not reloaded. It only refreshes the DOM (Document Object Model) for the required section. So, this reduces the overhead loading of the website.

So, now as we know what is Javascript & JQuery and how angular came into the picture. Moving ahead in this article, we will look through the features of angular and understand how to work with Angular.

Angular Tutorial

Angular is a TypeScript-based open-source front-end web application platform led by the Angular Team at Google and by a community of individuals and corporations. Angular is a complete rewrite from the same team that built AngularJS. But let me tell you that Angular is completely different from AngularJS. Let us understand the differences between Angular and AngularJS.

Differences between Angular and AngularJS

  • The architecture of an Angular application is different from AngularJS. The main building blocks for Angular are modules, components, templates, metadata, data binding, directives, services, and dependency injection. We will be looking at it in a while.
  • Angular was a complete rewrite of AngularJS.
  • Angular does not have a concept of “scope” or controllers instead, it uses a hierarchy of components as its main architectural concept.
  • Angular has a simpler expression syntax, focusing on “[ ]” for property binding, and “( )” for event binding
  • Mobile development — Desktop development is much easier when mobile performance issues are handled first. Thus, Angular first handles mobile development.
  • Modularity — Angular follows modularity. Similar functionalities are kept together in the same modules. This gives Angular a lighter & faster core.

Angular recommends the use of Microsoft’s TypeScript language, which introduces the following features:

  • Class-based Object Oriented Programming
  • Static Typing

TypeScript is a superset of ECMAScript 6 (ES6) and is backward compatible with ECMAScript 5. Angular also includes the benefits of ES6:

  • Iterators
  • For/Of loops
  • Reflection
  • Improved dependency injection — bindings make it possible for dependencies to be named
  • Dynamic loading
  • Asynchronous template compilation
  • Simpler Routing
  • Replacing controllers and $scope with components and directives — a component is a directive with a template
  • Support reactive programming using RxJS

Moving ahead in this Angular tutorial, let’s understand the features of Angular.

Angular Features

Cross Platform

  • Progressive web apps

It uses modern web platform capabilities to deliver an app-like experience. It gives high performance, offline, and zero-step installation. So, working with Angular is pretty much easy.

  • Native

You can build native mobile apps with strategies using Ionic Framework, NativeScript, and React Native.

  • Desktop

Create desktop-installed apps across Mac, Windows, and Linux using the same Angular methods you’ve learned for the web plus.

Speed and Performance

  • Code generation

Angular turns your templates into code that’s highly optimized for JavaScript virtual machines, giving you all the benefits of hand-written code with the productivity of a framework.

  • Universal

You can use any technology with Angular for serving the application like Node.js, .NET, PHP and other servers.

  • Code splitting

Angular apps load quickly with the new Component Router, which delivers automatic code-splitting, so users only load code required to render the view they request.

Productivity

  • Templates

Quickly create UI views with simple and powerful template syntax.

  • Angular CLI

Command line tools: You can easily and quickly start building components, adding components, testing them, and then, instantly deploy them using Angular CLI.

  • IDEs

Get intelligent code completion, instant errors, and other feedback in popular editors and IDEs like Microsoft’s VS Code.

Full Development Story

  • Testing

With Karma for unit tests, you can identify your mistake on the fly and Protractor makes your scenario tests run faster and in a stable manner.

Moving on to the most important part of our Angular tutorial, let us discuss the building blocks of Angular.

Building Blocks of Angular

The main building blocks of Angular are:

  • Modules
  • Components
  • Templates
  • Metadata
  • Data binding
  • Directives
  • Services
  • Dependency injection

Next, in our Angular Tutorial, let us talk about each of them in detail. Let us first understand, what are modules?

Modules

Angular apps are modular and to maintain modularity, we have Angular modules or you can say NgModules. Every Angular app contains at least one Angular module, i.e. the root module. Generally, it is named as AppModule. The root module can be the only module in a small application. While most of the apps have multiple modules. You can say, a module is a cohesive block of code with a related set of capabilities which have a specific application domain or a workflow. Any angular module is a class with @NgModule decorator.

Decorators are functions that modify JavaScript classes. Decorators are basically used for attaching metadata to classes so that, it knows the configuration of those classes and how they should work. NgModule is a decorator function that takes metadata object whose properties describe the module. The properties are:

  • declarations: The classes that are related to views and it belong to this module. There are three classes of Angular that can contain view: components, directives and pipes. We will talk about them in a while.
  • exports: The classes that should be accessible to the components of other modules.
  • imports: Modules whose classes are needed by the component of this module.
  • providers: Services present in one of the modules which is to be used in the other modules or components. Once a service is included in the providers it becomes accessible in all parts of that application
  • bootstrap: The root component which is the main view of the application. This root module only has this property and it indicates the component that is to be bootstrapped.

Let us take a look how the root module (i.e. src/app/app.module.ts) looks like:

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

@NgModule({
imports:[ BrowserModule ],
providers: [ BookList ],
declarations: [ AppComponent ],
exports: [],
bootstrap: [ AppComponent ]
})

export class AppModule { }

A root module generally doesn’t export it’s class because as root module is the one which imports other modules & components to use them. We bootstrap the AppModule in a main.ts file, where we specify the bootstrap module and inside the bootstrap module, contains the bootstrap component.

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);

Angular libraries

Angular gives us a collection of JavaScript modules (library modules) which provide various functionalities. Each Angular library has @angular prefix, like @angular/core, @angular/compiler, @angular/compiler-cli, @angular/http, @angular/router. You can install them using the npm package manager and import parts of them with JavaScript import statements.

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

In the above example, Angular’s Component decorator is imported from the @angular/core library.

Now moving ahead in Angular Tutorial, let us understand the next and one of the important building block of Angular, i.e. Component.

Components

A component controls one or more section on the screen called a view. For example, if you are building a movie list application, you can have components like App Component (the bootstrapped component), Movielist Component, Movie Description Component, etc.

Inside the component, you define a component’s application logic i.e. how does it support the view — inside a class. The class interacts with the view through an API of properties and methods.

Every app has a main component which is bootstrapped inside the main module, i.e AppComponent.

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

@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent{
title = 'app works!';
}

So, after taking a look at the bootstrapped component. Now let us take a look at one more component i.e. Movies Component as to give you more idea about the component.

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

@Component({
selector: 'app-movies',
templateUrl: './movies.component.html',
styleUrls: ['./movies.component.css']
})

export class MoviesComponent implements OnInit {
movies: any[];
ngOnInit() {
getMovies()({
this.movies = movies;
})
}
}

Here, first, we import the components and dependencies that we require in our component using the import keyword. Then, we attach the metadata of the component using @Component decorator. The first property is the selector, which targets the keyword and dumps the data within selected tag. You can attach the view using two ways: either you can attach template property and specify the template here or you can use templateUrl and provide the path of the file which contains the template. We will be discussing the template in detail later. The third property is styleUrls which gives the path of the CSS style sheet.

Then after the metadata, we specify the logic of the component which resides inside the class. We specify the constructor and inside it, we specify the variables and method, which needs to be initialized when the class is created. Then we also have ngOnInit method that is called when a component is instantiated.

Moving to next building block in our Angular tutorial, i.e. Templates.

Templates

You associate component’s view with its companion template. A template is nothing but a form of HTML tags that tells Angular about how to render the component. A template looks like regular HTML, except for a few differences. Here is a template for our Movie Component as we discussed above:

<app-navbar></app-navbar>


<div class ="container">
<flash-messages></flash-messages>
<router-outlet></router-outlet>
</div>

Here we have custom tags like <app-navbar>.

Metadata

Metadata tells Angular how to process a class. To tell Angular that MovieList Component is a component, metadata is attached to the class. In TypeScript, you attach metadata by using a decorator. In the below code, you can see metadata attached to the Movie Component:

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

@Component({
selector: 'app-movies',
templateUrl: './movies.component.html',
styleUrls: ['./movies.component.css']
})

Here is the @Component decorator, which identifies the class immediately below it as a component class. The @Component decorator takes the required configuration object which Angular needs to create and present the component and its view.

The most important configurations of @Component decorator are:

  • selector: Selector tells Angular to create and insert an instance of this component where it finds <app-movies> tag. For example, if an app’s HTML contains <app-movies></app-movies>, then Angular inserts an instance of the MovieListComponent view between those tags.
  • templateUrl: It contains the path of this component’s HTML template.
  • providers: An array of dependency injection providers for services that the component requires. This is one way to tell Angular that the component’s constructor requires a MovieService to get the list of movies to display.

The metadata in the @Component tells Angular where to get the major building blocks you specify for the component. The template, metadata, and component together describe a view. The architectural takeaway is that you must add metadata to your code so that Angular knows what to do.

Data Binding

If you are not using a framework, you have to push data values into the HTML controls and turn user responses into some actions and value updates. Writing such push/pull logic is tedious, error-prone, and a nightmare to read. Angular supports data binding, a mechanism for coordinating parts of a template with parts of a component. You should add binding markup to the template HTML to tell Angular how to connect both sides.

Each form has a direction — to the DOM, from the DOM, or in both directions.

<li> {{movie.name}}</li>


<movie-detail [movie]="selectedMovie"></movie-detail>


<li (click)="selectMovie(Movie)"></li>
  • The {{movie.name}} interpolation displays the component’s name property value within the <li> element.
  • The [movie] property binding passes the value of selectedMovie from the parent MovieListComponent to the movie property of the child MovieDetailComponent.
  • The(click) event binding calls the component’s selectMovie method when the user clicks a movies’s name.

Two-way data binding is an important part as it combines property and event binding in a single notation, using the ngModel directive. Here’s an example from the MovieDetailComponent template:

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

In two-way binding, a data property value flows to the input box from the component as with property binding. The user’s changes also flow back to the component, resetting the property to the latest value, as with event binding. Angular processes all data bindings once per JavaScript event cycle, from the root of the application component tree through all child components.

Data binding plays an important role in communication between a template and its component. Data binding is also important for communication between parent and child components.

Moving further in this Angular Tutorial, we will discuss about next building block, i.e. 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 @Component decorator is actually a @Directive decorator extended with template-oriented features.

While a component is technically a directive, components are so distinctive and central to Angular applications that this architectural overview separates components from directives.

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

Directive tends 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.

This example template uses two built-in structural directives:

<li *ngFor="let movie of movies"></li> 
<movie-detail *ngIf="selectedMovie"></movie-detail>
  • *ngFor tells Angular to retrieve one <li> per movie in the movies
  • *ngIf includes the MovieDetail component only if a selected movie exists.

Attribute directives alter the appearance or behavior of an existing element. In templates, they look like regular HTML attributes. The ngModel directive, which implements two-way data binding, is an example of an attribute directive. ngModel modifies the behavior of an existing element by setting its display value property and responding to change events.

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

Angular has a few more directives that either alter the layout structure (for example, ngSwitch) or modify aspects of DOM elements and components (for example, ngStyle and ngClass).

You can also write your own directives, i.e. Custom Directive.

Services

Service is a broad category encompassing any value, function, or feature that your application needs. A service is typically a class with a well-defined purpose. Anything can be a service. Examples include:

  • logging service
  • data service
  • message bus
  • tax calculator
  • application configuration

Angular has no definition of a service. There is no service base class, and no place to register a service. Yet services are fundamental to any Angular application. Components are the consumers of services.

Here’s an example of a service class where we are using Google’s Firebase as database and importing the movie-list:

import { Injectable } from '@angular/core';
import { AngularFire, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2';
import { Movie } from '../interfaces/movie'

@Injectable()

export class FirebaseService {
movies: FirebaseListObservable<any[]>;
movie: FirebaseObjectObservable<any>;
titles: FirebaseListObservable<any[]>;
term: string = 'Incep';

constructor(privateaf: AngularFire) { }

getMovies()
{
this.movies = this.af.database.list('/movies') asFirebaseListObservable<Movie[]>;
returnthis.movies;
}

getMovieDetails(id)
{
this.movie = this.af.database.object('/movies/'+id) asFirebaseObjectObservable<Movie>;
return this.movie;
}

searchMovies()
{
this.movies = this.af.database.list('/movies',{
query: {
orderByChild:'title',
startAt:this.term,
endAt:this.term + "\uf8ff",
value:'once'
}
} ) as FirebaseListObservable<Movie[]>;
return this.movies;
}
}

Services are everywhere. Component classes don’t fetch data from the server, validate user input, or log directly to the console. They delegate such tasks to services.

A component’s job is to enable the user experience and nothing more. It mediates between the view (rendered by the template) and the application logic. A good component presents properties and methods for data binding. Angular does help you follow these principles by making it easy to factor your application logic into services and make those services available to components through dependency injection.

So, now let us understand dependency injection, in this article.

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. Angular can tell which services a component needs by looking at the types of its constructor parameters.

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.

In the below example you can see, we are registering a provider of the Firebase Service with the injector. A provider is something that can create or return a service, typically the service class itself. You can register providers in modules or in components.

In general, add providers to the root module so that the same instance of a service is available everywhere as shown in the code below.

@NgModule({
declarations: [
AppComponent,
HomeComponent,
MoviesComponent,
NavbarComponent,
MovieDetailsComponent,
AboutComponent,
BoldTextDirective,
MovieSearchComponent,
],

imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(routes),
AngularFireModule.initializeApp(firebaseConfig,firebaseAuthConfig),
FlashMessagesModule
],

providers: [FirebaseService],
bootstrap: [AppComponent]
})

export class AppModule { }

Alternatively, you can register a service at a component level in the providers property of the @Component decorator:

import { Component } from '@angular/core';
import { FirebaseService } from './services/firebase.service';

@Component({
selector:'app-root',
templateUrl:'./app.component.html',
styleUrls: ['./app.component.css'],
providers: [FirebaseService]
})
export class AppComponent {
title = 'app works!';
}

Registering at a component level means you get a new instance of the service with each new instance of that component.

Concluding about dependency injection, you can say that:

  • Dependency injection is wired into the Angular framework and used everywhere.
  • The injector is the main mechanism.
  • An injector maintains a container of service instances that it created.
  • An injector can create a new service instance from a provider.
  • A provider is a recipe for creating a service.
  • Register providers with injectors.

This brings us to the end of “Angular Tutorial” article. If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, Python, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Web Development.

1. ReactJS Tutorial

2. React Components

3. React Router v4 Tutorial

4. React Redux Tutorial

5. Angular Directive Tutorial

6. Animating AngularJS Apps with ngAnimate Directive

7. NodeJS Tutorial

8. PHP Tutorial

9. JQuery Tutorial

10. Top 10 JavaScript Frameworks

11. Build a CRUD Application Using Node.js and MySQL

12. Build CRUD Application using Node.JS and MongoDB

13. Build REST API with Node.js

14. Best 3 Ways to Make Node.js Requests

15. HTML vs HTML5

16. What is REST API?

17. Flutter vs React Native

18. How To Dockerize a Node.js App?

19. How to Build a JavaScript Calculator?

Originally published at www.edureka.co on May 30, 2017.

--

--

Zulaikha Geer
Edureka

A technology enthusiast with expertise in several different domains including Data Science, DevOps and Web Development.