Back to Top

Angularjs 2 Tutorial for Beginners

Angular JS 2 Tutorial

You all have created an application using the Angular 1.x and Once Angular 2.0 entered in the market everybody will start to ask to upgrade the site to the latest version. You can’t throw the old application away. All you have to do is to create a bridge between Angular 1.0 and Angular 2.0 or create a hybrid application of Angular 1.0 and Angular 2.0 and then gradually convert the site from older to the latest version. This Angular JS 2 Tutorial designed for those who want to learn the basics of AngularJS 2

Today I am going to share about how you can use the Angular Js 2 in this Angular JS 2 Tutorial but before starting, I hope you are aware of previous articles. If not,I have covered the How to get started with AngularJS, and Angular JS MVC Architecture with an example . After that, I have covered the How to use Data Binding and Directives in Angular JS. Now I am going to covers the Angularjs 2 with TypeScript Tutorial for Beginners

Let’s start with the pain points of the Angular JS 1 and to get to know why do you require to learn the Angular JS 2. So, What’s wrong in Angular JS 1? You might face some problems using the Angular JS 1 if you have built the real-time application.

Few Problems in Angular JS 1.x

There few problems in the Angular JS 1.o which are

  1. It’s learning curve is hard.
  2. You have to manually apply stuff and angular JS to do magic.
  3. There are two option factory and services in Angular JS and most of the developers are confused, when to use factory and when to services.
  4. Beside this ,there is a big problem of efficiency, a frame rendering that is done due to angular code in the browser sucks. If you have DOM heavy application, you will find performance issues in Angular.
  5. Especially in Internet Explorer, there is a scope refreshing problem in internal changes. You have to add lot of watches and other stuff.

This is all are the reason that React over Angular JS boom in the market. People have seen that React Js is faster than the Angular JS because it works in particular chunk and that two-way data binding kills. It is required but in some cases, not everywhere to do two-way data binding. Two way data binding is not required in all 90% cases. There are just 10% cases where two way data binding. Generally, you have to set up one way binding from your class to DOM and DOM to your class.

All the painful problematic things of Angular JS 1 is being resolved in Angular JS 2. They came up with new change mechanism using zone. Basically, they have the zone that is doing change detection smartly internally and you don’t have to do $apply every time. They have removed the concept of services, factory etc all together. It will simply communicate through classes. It also has the thing which is component based programming which created a hype in the market.

In Angular JS 1, there is no direct way to create components, You have to create directives and then do some acts and it works as the component, whereas in Angular 2.0 is based on the component.You can club the small components to create a big component that is the main philosophy of Angular JS 2.

Overview

Here is the list of things cover in this article:

  • Overview of Angular 2.0 application architecture.
  • Lifecycle hooks: From Angular JS 1, provides the lifecycle hooks that is very helpful otherwise in angular 1 have to do lot of research to do when the DOM gets ready.
  • Improvements over Angular js 1.0
  • Building sample application in Angular 2.0

Architecture of Angular JS 2.0

architecture-of-angular-js-2-0

If you see the architecture, it recalls components. Here in this architecture where you find the gears or settings items those are basically classes, a JavaScript code. Every component has two parts. Classes and templates(HTML associated with it). This is not new in Angular JS 2.0. The class was there when you created directives, also have controller and template associated with it. Here It provides MetaData.

Using MetaData, you are instructing angular about what this class does and that is the usage of Metadata. Now, here you don’t have two way data binding.It only performs the single binding. Either property binding or event binding. It still has directives here and same as Angular 1.0. The injector is used to dependency injections. The injector is slightly optimized to gain the performance and reduce the complexity. Dependencies are the class,values etc as dependencies unlike angular 1 that services and factory dependencies.In the latest version, you can keep anything as the dependency.

Modules comprise the multiple components and create a module. When you combine multiple modules to create an application. That is what overall architecture of Angular 2.0

Now, Let see the main building blocks of Angular 2.0. You will not find anything out of this in Angular 2.0 and will not have confusion when to use which one. Here don’t have common like factory and service. Everything has well-defined usage and guidelines when to use which one.

Building blocks of Angular JS 2.0

  • Modules : Modules are the comprises of multiple components and angular JS 2.0 should have at least one module.
  • Components : Multiple small components comprises to create a one big module.
  • Templates : HTML part associated with your code base templates.
  • MetaData : This is a new thing that came into the angular. It is instructing your class what kind of things your class can do. You can create any class and adopt with metadata. Everything is revolving around metadata what meta you apply to your class and that class will do the same.
  • Data Bindings : Data binding is the main reason to use Angular JS in application. Two way data binding is removed and separated as property and event binding. You can merge both property and event binding to get two way data binding.
  • Directives : Directives are slightly changed than older version. Here Directives are used for non structural changes.
  • Services : Services are normal class which interact with APIs.
  • Dependency Injection(DI): Dependency Injection is to inject and maintain the singleton class.

These are the main blocks of Angular JS 2.0. Now I will explain each and every blocks one by one in detail:

Modules:

  • Angular Js 2.0 has modularity system called Angular modules or NgModules.
  • Every Angular JS app has at least one module, the root module. There should be root module which gives angular a starting point to start the application.
  • An Angular module, whether a root or feature, is a class with a @NgModule decorator. Any Angular JS 2.0 class can become module by adding @NgModule decorator. As I told, Everything got from meta.Any class annotated with @NgModule will become module of module and it has to comprise few of the interfaces of modules.

NgModule decorator has below parameters:

  1. Decorations
  2. Exports
  3. Imports
  4. Providers
  5. Bootstrap

Components and Templates:

Similar to directives, It is a small portion in your view.A component controls a patch of the system called a view. Any small portion according to your business logic in your application is a component.

A business logic and code goes inside the component’s class which interacts with template via API properties and methods

The component comprises in two parts. One is component core which is you see in curly braces({}). One component can comprise many components.

MetaData

MetaData tells angular JS how to process a class when you annotate with decorators, Angular JS 2 knows what is it.

Angular JS 2.0 metadata decorators are

  1. @NgModule : For declaring module
  2. @Component : For declaring component
  3. @Directive : For declaring directive
  4. @Service : For declaring service
  5. @Injectable : To tell Angular JS 2.o that service is injectable.

So this is the usage of the MetaData in Angular JS 2.

Data Binding:

As I told now binding is separated, not support two way binding. It has turn into four different things.It is binding a property from the component(class) to template, a binding event from template to the class and vice versa.
Angular supports database mechanism for coordinating parts of the template with parts of the component.

There are four forms of data binding syntax, each form has a direction

  • To the DOM
  • From the DOM
  • In both Direction

data binding angular js 2

This is called property binding. This is core traditional way of defining value in curly braces. Whatever value is defining component,will go there. It is an again a single way.

Here, It will not work for two way binding. In Angular JS 1.0 if you want to make it single way, you have to append the double colon(::) but here in Angular JS 2, It is by default a single way. This way performance of the application will be improved. You don’t have to register the listeners,have to create fewer watchers and that will give you a speed of rendering and printing in the browser.

Another way to do the same thing is via the property.If you have to define properly of particular tag, you have to use:

This is again a single way binding.

Now, things come from the DOM. In DOM, the user can only do mouse move, click and type. Nothing else. So, There are only a few events that user can DOM on the browser which you can handle with the event binding.

In Angular 1, You were using ng-click and function name,here it’s syntax is like below:

SYNTAX:

This is also a single way binding from your DOM to your class.The last one, When you combine the round bracket and square bracket, that has become the two way data binding.

SYNTAX:

This will become two way data binding from your DOM to component and Component to DOM.As a developer, You have to set mind to understand where to use which binding in your application. Now, the binding is broken into two parts, so performance will be improved so far.

Data Binding between Component – Template

Data Binding between Component - Template

There are two things happen between components. One is data binding between components. Among the component will use property binding and next is event binding. A binding in one component happens like an above image.

Data Binding between Parent – Child Component

 Data Binding between Parent and Child Component

You have to define the outputs and inputs of your components then only you can interact with your parent. The mechanism is like from parent component, you can use property binding to set the property inside the child component and from the child, you can use event binding to pass the event. It is similar to event broadcast.

Directives

A directive is a class with directive metadata(@Directive). A component is a directive-with-a-template.

A thin line difference between directive and components and that difference is directive doesn’t have templates. A @component decorator is actually a @Directive decorator extended with template-oriented features.

Internally component inherits the directives. Inheritance root has the component derived from directives. The directive is the parent class.

Two kinds of directive exist

  1. Structural Directives – alter layout by adding , removing and replacing elements in DOM(e.g., ngFor, ngIf). It brings the structural changes in your application.
  2. Attribute Directives – alter the appearance or behaviour of an existing element in templates they look like regular HTML attributes, hence the name (e.g, ngModel, ngStyle, ngClass). Attributes Directives are those who change style, look and feel of application of the element.

Angular JS 1.0 have a number of directives which are even quite difficult to remember all of them whereas, in Angular JS 2, there are only a few directives so you can easily remember and use when required.

Services

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

Exa,
Logging
Data
Message bus
Tax calculation
REST services

This is just a class. You are mostly using services in the component.

Dependency Injection

It is a way to supply a new instance of a class with the fully formed dependencies it requires. Dependency Injection is used to follow singleton pattern. If you are creating a class and you need to create an object, that needs to be a singleton. If you are using Dependency Injection, that class instance will not be created again. It will be beneficial to memory as well as speed.

Most dependencies are services. The injector will check the instance and if not, create the instance and store the reference and give it to back.

Key points about Dependency Injection:

  • 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 services instance from a provider
  • A Provider is a recipe for creating a service.
  • Register provides with injectors.

So, That is how Dependency Injection works.

LifeCycle Hooks:

  1. ngOnChanges – When an input/output binding value changes.
  2. ngOnInit – After the first ngOnchanges. Similar to ng-init in Angular 1.x
  3. ngDoCheck – Developer’s custom change detection.
  4. ngAfterContentInit – After component content initialized
  5. ngAfterContentChecked – After every check of component content
  6. ngAfterViewInit – After component’s view(s) are initialized. It is a DOM event.
  7. ngAfterViewChecked – After every check of a component’s view(s)
  8. ngOnDestroy – just before the directive is destroyed.

Key features provided by Angular JS 2.0

  • Animation
  • Change detection using zones: Dijest cycle is the change detection which was creating performance issue in Angular JS 1.x whereas it is here improved change detection with the performance.
  • Events
  • Forms
  • HTTP
  • Lifecycle hooks
  • PIPES (filters)
  • Router: for routing mostly used UI Router which functionality is in built in the Angular JS 2. It is similar to UI.
  • Testing: You can easily test the Angular JS components.
  • Ahead-Of-Time(AOT) compilation: In Angular JS,It compiles the whole application before start displaying the file in the browser. With Ahead-Of-Time, You can create javascript file which is precompiled into native JavaScript code. Everything will be done Ahead-Of-Time on the server side one time which reduces the compilation time. There are benchmarking result and prove that faster.

Improvements over Angular 1.0

  1. Performance Improvements
  2. Mobile Support
  3. Typescript
  4. No $scope in Angular JS 2
  5. Component based programming
  6. JSON based route config is more easy to edit.
  7. Hierarchical dependency injection system
  8. File size of Angular JS 2 is less than Angular JS 1
  9. Ahead-Of-Time
  10. Good support for data architecture like RxJS and Redux

Let’s start writing the application:

Building Sample Application

Here I am showing basic Angular JS application using typescript. Include all dependent files. Exa, system.js, zone.js etc

I am going to create an application. First I will create app folder and component in it. Let me define the first component. There is one specific guideline in Angular JS 2, how you should name your file, class, and directives.

Whenever you need to create the component, the file extension is like .component.ts and file name.component.ts is the full name.

hello-world.component.ts

First of all , @Component is a decorator ,we are using here to define the component. There are few properties in the decorator. Here, I have used selector and template. Selector says what would be the name of your tag. I have used HTML tags here in template property. You can use template URL as well in template property.

My First hello world component is ready. As I told, there is at least one module in Angular 2 Application, You have to create one module for hello world application. Let’s create hello world module.

Hello-world.module.ts

In Declaration, define the components this module is going to use. You have to import HelloWorldComponent. This is the first module of the application and this is only the module using throughout the application so this will become the root module of the application. Whenever you create root module, must have the bootstrap attribute. One more thing you need to do is, you need to import BrowserModule inside imports.So I have included it.

Here I am done with defining the module. Now, let’s bootstrap the application.Here,You have to create one more file main.ts and doing the bootstrapping. First of all, import the platformBrowserDynamic module and HelloWorldModule.

Main.ts

HTML

Finally, Add the HTML code into this or in the new HTML file. Here add some core js files.Next, write the script and map the app to the file.app will tell that what is the main file.In body tag, write the tag you have used in the selector property here.

That’s t what you need to do with your hello world application. Now run the application in the browser. It will output the content.

Do let me know, are you using Angular JS latest version for your application? If you are using an older version of the Angular JS, Try the Angular JS 2 now and I would love to hear your review & feedback in the comments below.

Share this article with your blogger friends on Facebook, Twitter, and Google Plus!

Share:
Share on Facebook0

Share on LinkedIn0Tweet about this on TwitterShare on Google+0Buffer this pageDigg thisShare on Reddit0

Leave a Reply

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

Most Popular Posts

How to use Flickr API with PHP

Posted on 4 years ago

Bhumi

JQuery Animation effects

Posted on 4 years ago

Bhumi

MySQL FULLTEXT Index and Search

Posted on 1 year ago

Bhumi

How To Install Bugzilla on Windows

Posted on 4 years ago

Bhumi

The Reader’s Poll – June 2015

Posted on 1 year ago

Bhumi

The Reader’s Poll – August 2014

Posted on 2 years ago

Bhumi

The Reader’s Poll – June 2014

Posted on 2 years ago

Bhumi

The Readers’ Poll – May 2014

Posted on 2 years ago

Bhumi

The Readers’ Poll – August 2013

Posted on 3 years ago

Bhumi