Angular 2 – Overview

Angular 2 – Overview ”; Previous Next Angular JS is an open source framework built over JavaScript. It was built by the developers at Google. This framework was used to overcome obstacles encountered while working with Single Page applications. Also, testing was considered as a key aspect while building the framework. It was ensured that the framework could be easily tested. The initial release of the framework was in October 2010. Features of Angular 2 Following are the key features of Angular 2 − Components − The earlier version of Angular had a focus of Controllers but now has changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time. TypeScript − The newer version of Angular is based on TypeScript. This is a superset of JavaScript and is maintained by Microsoft. Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications. In addition, Angular 2 has better event-handling capabilities, powerful templates, and better support for mobile devices. Components of Angular 2 Angular 2 has the following components − Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task. Component − This can be used to bring the modules together. Templates − This is used to define the views of an Angular JS application. Metadata − This can be used to add more data to an Angular JS class. Service − This is used to create components which can be shared across the entire application. We will discuss all these components in detail in the subsequent chapters of this tutorial. The official site for Angular is https://angular.io/ The site has all information and documentation about Angular 2. Print Page Previous Next Advertisements ”;

Angular 2 – Modules

Angular 2 – Modules ”; Previous Next Modules are used in Angular JS to put logical boundaries in your application. Hence, instead of coding everything into one application, you can instead build everything into separate modules to separate the functionality of your application. Let’s inspect the code which gets added to the demo application. In Visual Studio code, go to the app.module.ts folder in your app folder. This is known as the root module class. The following code will be present in the app.module.ts file. import { NgModule } from ”@angular/core”; import { BrowserModule } from ”@angular/platform-browser”; import { AppComponent } from ”./app.component”; @NgModule ({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } Let’s go through each line of the code in detail. The import statement is used to import functionality from the existing modules. Thus, the first 3 statements are used to import the NgModule, BrowserModule and AppComponent modules into this module. The NgModule decorator is used to later on define the imports, declarations, and bootstrapping options. The BrowserModule is required by default for any web based angular application. The bootstrap option tells Angular which Component to bootstrap in the application. A module is made up of the following parts − Bootstrap array − This is used to tell Angular JS which components need to be loaded so that its functionality can be accessed in the application. Once you include the component in the bootstrap array, you need to declare them so that they can be used across other components in the Angular JS application. Export array − This is used to export components, directives, and pipes which can then be used in other modules. Import array − Just like the export array, the import array can be used to import the functionality from other Angular JS modules. Print Page Previous Next Advertisements ”;

Angular 2 – Third Party Controls

Angular 2 – Third Party Controls ”; Previous Next Angular 2 allows you to work with any third party controls. Once you decide on the control to implement, you need to perform the following steps − Step 1 − Install the component using the npm command. For example, we will install the ng2-pagination third party control via the following command. npm install ng2-pagination –save Once done, you will see that the component is successfully installed. Step 2 − Include the component in the app.module.ts file. import { NgModule } from ”@angular/core”; import { BrowserModule } from ”@angular/platform-browser”; import { AppComponent } from ”./app.component”; import {Ng2PaginationModule} from ”ng2-pagination”; @NgModule ({ imports: [ BrowserModule,Ng2PaginationModule], declarations: [ AppComponent], bootstrap: [ AppComponent ] }) export class AppModule { } Step 3 − Finally, implement the component in your app.component.ts file. import { Component } from ”@angular/core”; import {PaginatePipe, PaginationService} from ”ng2-pagination”; @Component ({ selector: ”my-app”, template: ” <ul> <li *ngFor = “let item of collection | paginate: { itemsPerPage: 5, currentPage: p }”> … </li> </ul> <pagination-controls (pageChange) = “p = $event”></pagination-controls> ” }) export class AppComponent { } Step 4 − Save all the code changes and refresh the browser, you will get the following output. In the above picture, you can see that the images have been stored as One.jpg and two.jpg in the Images folder. Step 5 − Change the code of the app.component.ts file to the following. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { appTitle: string = ”Welcome”; appList: any[] = [{ “ID”: “1”, “Name”: “One”, “url”: ”app/Images/One.jpg” }, { “ID”: “2”, “Name”: “Two”, “url”: ”app/Images/two.jpg” } ]; } Following points need to be noted about the above code. We are defining an array called appList which is of the type any. This is so that it can store any type of element. We are defining 2 elements. Each element has 3 properties, ID, Name and url. The URL for each element is the relative path to the 2 images. Step 6 − Make the following changes to the app/app.component.html file which is your template file. <div *ngFor = ”let lst of appList”> <ul> <li>{{lst.ID}}</li> <li>{{lst.Name}}</li> <img [src] = ”lst.url”> </ul> </div> Following points need to be noted about the above program − The ngFor directive is used to iterate through all the elements of the appList property. For each property, it is using the list element to display an image. The src property of the img tag is then bounded to the url property of appList in our class. Step 7 − Save all the code changes and refresh the browser, you will get the following output. From the output, you can clearly see that the images have been picked up and shown in the output. Print Page Previous Next Advertisements ”;

Angular 2 – Error Handling

Angular 2 – Error Handling ”; Previous Next Angular 2 applications have the option of error handling. This is done by including the ReactJS catch library and then using the catch function. Let’s see the code required for error handling. This code can be added on top of the chapter for CRUD operations using http. In the product.service.ts file, enter the following code − import { Injectable } from ”@angular/core”; import { Http , Response } from ”@angular/http”; import { Observable } from ”rxjs/Observable”; import ”rxjs/add/operator/map”; import ”rxjs/add/operator/do”; import ”rxjs/add/operator/catch”; import { IProduct } from ”./product”; @Injectable() export class ProductService { private _producturl = ”app/products.json”; constructor(private _http: Http){} getproducts(): Observable<IProduct[]> { return this._http.get(this._producturl) .map((response: Response) => <IProduct[]> response.json()) .do(data => console.log(JSON.stringify(data))) .catch(this.handleError); } private handleError(error: Response) { console.error(error); return Observable.throw(error.json().error()); } } The catch function contains a link to the Error Handler function. In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue. Now, whenever you get an error it will be redirected to the error console of the browser. Print Page Previous Next Advertisements ”;

Angular 2 – Hello World

Angular 2 – Hello World ”; Previous Next There are various ways to get started with your first Angular JS application. One way is to do everything from scratch which is the most difficult and not the preferred way. Due to the many dependencies, it becomes difficult to get this setup. Another way is to use the quick start at Angular Github. This contains the necessary code to get started. This is normally what is opted by all developers and this is what we will show for the Hello World application. The final way is to use Angular CLI. We will discuss this in detail in a separate chapter. Following are the steps to get a sample application up and running via github. Step 1 − Go the github url – https://github.com/angular/quickstart Step 2 − Go to your command prompt, create a project directory. This can be an empty directory. In our example, we have created a directory called Project. Step 3 − Next, in the command prompt, go to this directory and issue the following command to clone the github repository on your local system. You can do this by issuing the following command − git clone https://github.com/angular/quickstart Demo This will create a sample Angular JS application on your local machine. Step 4 − Open the code in Visual Studio code. Step 5 − Go to the command prompt and in your project folder again and issue the following command − npm install This will install all the necessary packages which are required for the Angular JS application to work. Once done, you should see a tree structure with all dependencies installed. Step 6 − Go to the folder Demo → src → app → app.component.ts. Find the following lines of code − import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: `<h1>Hello {{name}}</h1>`, }) export class AppComponent { name = ”Angular”; } And replace the Angular keyword with World as shown below − import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: `<h1>Hello {{name}}</h1>`, }) export class AppComponent { name = ”World”; } There are other files that get created as part of the project creation for Angular 2 application. At the moment, you don’t need to bother about the other code files because these are all included as part of your Angular 2 application and don’t need to be changed for the Hello World application. We will be discussing these files in the subsequent chapters in detail. Note − Visual Studio Code will automatically compile all your files and create JavaScript files for all your typescript files. Step 7 − Now go to your command prompt and issue the command npm start. This will cause the Node package manager to start a lite web server and launch your Angular application. The Angular JS application will now launch in the browser and you will see “Hello World” in the browser as shown in the following screenshot. Deployment This topic focuses on the deployment of the above Hello world application. Since this is an Angular JS application, it can be deployed onto any platform. Your development can be on any platform. In this case, it will be on Windows using Visual Studio code. Now let’s look at two deployment options. Deployment on NGNIX Servers on Windows Note that you can use any web server on any platform to host Angular JS applications. In this case, we will take the example of NGNIX which is a popular web server. Step 1 − Download the NGNIX web server from the following url http://nginx.org/en/download.html Step 2 − After extracting the downloaded zip file, run the nginx exe component which will make the web server run in the background. You will then be able to go to the home page in the url – http://localhost Step 3 − Go to Angular JS project folder in Windows explorer. Step 4 − Copy the Project → Demo → node-modules folder. Step 5 − Copy all the contents from the Project → Demo → src folder. Step 6 − Copy all contents to the nginx/html folder. Now go to the URL − http://localhost, you will actually see the hello world application as shown in the following screenshot. Setting Up on Ubuntu Now let’s see how to host the same hello world application onto an Ubuntu server. Step 1 − Issue the following commands on your Ubuntu server to install nginx. apt-get update The above command will ensure all the packages on the system are up to date. Once done, the system should be up to date. Step 2 − Now, install GIT on the Ubuntu server by issuing the following command. sudo apt-get install git Once done, GIT will be installed on the system. Step 3 − To check the git version, issue the following command. sudo git –version Step 4 − Install npm which is the node package manager on Ubuntu. To do this, issue the following command. sudo apt-get install npm Once done, npm will be installed on the system. Step 5 − To check the npm version, issue the following command. sudo npm -version Step 6 − Next, install nodejs. This can be done via the following command. sudo npm install nodejs Step 7 − To see the version of Node.js, just issue the following command. sudo nodejs –version Step 8 − Create a project folder and download the github starter project using the following git command. git clone https://github.com/angular/quickstart Demo This will download all the files on the local system. You can navigate through the folder to see the files have been successfully downloaded from github. Step 9 − Next issue the following command for npm. npm install This will install all the necessary packages which are required for Angular JS application to work. Once done, you will see all the dependencies installed on the system. Step 10 − Go to the folder Demo → src → app → app.component.ts. Use the vim editor

Angular 2 – Components

Angular 2 – Components ”; Previous Next Components are a logical piece of code for Angular JS application. A Component consists of the following − Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives. Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript. Metadata − This has the extra data defined for the Angular class. It is defined with a decorator. Let’s now go to the app.component.ts file and create our first Angular component. Let’s add the following code to the file and look at each aspect in detail. Class The class decorator. The class is defined in TypeScript. The class normally has the following syntax in TypeScript. Syntax class classname { Propertyname: PropertyType = Value } Parameters Classname − This is the name to be given to the class. Propertyname − This is the name to be given to the property. PropertyType − Since TypeScript is strongly typed, you need to give a type to the property. Value − This is the value to be given to the property. Example export class AppComponent { appTitle: string = ”Welcome”; } In the example, the following things need to be noted − We are defining a class called AppComponent. The export keyword is used so that the component can be used in other modules in the Angular JS application. appTitle is the name of the property. The property is given the type of string. The property is given a value of ‘Welcome’. Template This is the view which needs to be rendered in the application. Syntax Template: ” <HTML code> class properties ” Parameters HTML Code − This is the HTML code which needs to be rendered in the application. Class properties − These are the properties of the class which can be referenced in the template. Example template: ” <div> <h1>{{appTitle}}</h1> <div>To Tutorials Point</div> </div> ” In the example, the following things need to be noted − We are defining the HTML code which will be rendered in our application We are also referencing the appTitle property from our class. Metadata This is used to decorate Angular JS class with additional information. Let’s take a look at the completed code with our class, template, and metadata. Example import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: ` <div> <h1>{{appTitle}}</h1> <div>To Tutorials Point</div> </div> `, }) export class AppComponent { appTitle: string = ”Welcome”; } In the above example, the following things need to be noted − We are using the import keyword to import the ‘Component’ decorator from the angular/core module. We are then using the decorator to define a component. The component has a selector called ‘my-app’. This is nothing but our custom html tag which can be used in our main html page. Now, let’s go to our index.html file in our code. Let’s make sure that the body tag now contains a reference to our custom tag in the component. Thus in the above case, we need to make sure that the body tag contains the following code − <body> <my-app></my-app> </body> Output Now if we go to the browser and see the output, we will see that the output is rendered as it is in the component. Print Page Previous Next Advertisements ”;

Angular 2 – Home

Angular 2 Tutorial PDF Version Quick Guide Resources Job Search Discussion Angular 2 is an open source JavaScript framework to build web applications in HTML and JavaScript. This tutorial looks at the various aspects of Angular 2 framework which includes the basics of the framework, the setup of Angular and how to work with the various aspects of the framework. Other topics discussed in the tutorial are advanced chapters such as interfaces, nested components and services within Angular. Topics such as routing, modules, and arrays are also dealt with in this tutorial. Audience This tutorial is for those who are interested in learning the new version of the Angular framework. The first version of the framework has been there for quite some time and it is only off-late that Angular 2 has become popular with the web development community. Prerequisites The user should be familiar with the basics of web development and JavaScript. Since the Angular framework is built on the JavaScript framework, it becomes easier for the user to understand Angular if they know JavaScript. Print Page Previous Next Advertisements ”;

Angular 2 – User Input

Angular 2 – User Input ”; Previous Next In Angular 2, you can make the use of DOM element structure of HTML to change the values of the elements at run time. Let’s look at some in detail. The Input Tag In the app.component.ts file place the following code. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: ” <div> <input [value] = “name” (input) = “name = $event.target.value”> {{name}} </div> ” }) export class AppComponent { } Following things need to be noted about the above code. [value] = ”username” − This is used to bind the expression username to the input element’s value property. (input) = ”expression” − This a declarative way of binding an expression to the input element’s input event. username = $event.target.value − The expression that gets executed when the input event is fired. $event − Is an expression exposed in event bindings by Angular, which has the value of the event’s payload. Once you save all the code changes and refresh the browser, you will get the following output. You can now type anything and the same input will reflect in the text next to the Input control. Click Input In the app.component.ts file place the following code. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: ”<button (click) = “onClickMe()”> Click Me </button> {{clickMessage}}” }) export class AppComponent { clickMessage = ”Hello”; onClickMe() { this.clickMessage = ”This tutorial!”; } } Once you save all the code changes and refresh the browser, you will get the following output. When you hit the Click Me button, you will get the following output. Print Page Previous Next Advertisements ”;

Angular 2 – Data Binding

Angular 2 – Data Binding ”; Previous Next Two-way binding was a functionality in Angular JS, but has been removed from Angular 2.x onwards. But now, since the event of classes in Angular 2, we can bind to properties in AngularJS class. Suppose if you had a class with a class name, a property which had a type and value. export class className { property: propertytype = value; } You could then bind the property of an html tag to the property of the class. <html tag htmlproperty = ”property”> The value of the property would then be assigned to the htmlproperty of the html. Let’s look at an example of how we can achieve data binding. In our example, we will look at displaying images wherein the images source will come from the properties in our class. Following are the steps to achieve this. Step 1 − Download any 2 images. For this example, we will download some simple images shown below. Step 2 − Store these images in a folder called Images in the app directory. If the images folder is not present, please create it. Step 3 − Add the following content in app.component.ts as shown below. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { appTitle: string = ”Welcome”; appList: any[] = [ { “ID”: “1”, “url”: ”app/Images/One.jpg” }, { “ID”: “2”, “url”: ”app/Images/Two.jpg” } ]; } Step 4 − Add the following content in app.component.html as shown below. <div *ngFor = ”let lst of appList”> <ul> <li>{{lst.ID}}</li> <img [src] = ”lst.url”> </ul> </div> In the above app.component.html file, we are accessing the images from the properties in our class. Output The output of the above program should be like this − Print Page Previous Next Advertisements ”;

Angular 2 – Navigation

Angular 2 – Navigation ”; Previous Next In Angular 2, it is also possible to carry out manual navigation. Following are the steps. Step 1 − Add the following code to the Inventory.component.ts file. import { Component } from ”@angular/core”; import { Router } from ”@angular/router”; @Component ({ selector: ”my-app”, template: ”Inventory <a class = “button” (click) = “onBack()”>Back to Products</a>” }) export class AppInventory { constructor(private _router: Router){} onBack(): void { this._router.navigate([”/Product”]); } } The following points need to be noted about the above program − Declare an html tag which has an onBack function tagged to the click event. Thus, when a user clicks this, they will be directed back to the Products page. In the onBack function, use the router.navigate to navigate to the required page. Step 2 − Now, save all the code and run the application using npm. Go to the browser, you will see the following output. Step 3 − Click the Inventory link. Step 4 − Click the ‘Back to products’ link, you will get the following output which takes you back to the Products page. Print Page Previous Next Advertisements ”;