Angular 2 – Custom Pipes

Angular 2 – Custom Pipes ”; Previous Next Angular 2 also has the facility to create custom pipes. The general way to define a custom pipe is as follows. import { Pipe, PipeTransform } from ”@angular/core”; @Pipe({name: ”Pipename”}) export class Pipeclass implements PipeTransform { transform(parameters): returntype { } } Where, ”Pipename” − This is the name of the pipe. Pipeclass − This is name of the class assigned to the custom pipe. Transform − This is the function to work with the pipe. Parameters − This are the parameters which are passed to the pipe. Returntype − This is the return type of the pipe. Let’s create a custom pipe that multiplies 2 numbers. We will then use that pipe in our component class. Step 1 − First, create a file called multiplier.pipe.ts. Step 2 − Place the following code in the above created file. import { Pipe, PipeTransform } from ”@angular/core”; @Pipe ({ name: ”Multiplier” }) export class MultiplierPipe implements PipeTransform { transform(value: number, multiply: string): number { let mul = parseFloat(multiply); return mul * value } } Following points need to be noted about the above code. We are first importing the Pipe and PipeTransform modules. Then, we are creating a Pipe with the name ”Multiplier”. Creating a class called MultiplierPipe that implements the PipeTransform module. The transform function will then take in the value and multiple parameter and output the multiplication of both numbers. Step 3 − In the app.component.ts file, place the following code. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: ”<p>Multiplier: {{2 | Multiplier: 10}}</p>” }) export class AppComponent { } Note − In our template, we use our new custom pipe. Step 4 − Ensure the following code is placed in the app.module.ts file. import { NgModule } from ”@angular/core”; import { BrowserModule } from ”@angular/platform-browser”; import { AppComponent } from ”./app.component”; import { MultiplierPipe } from ”./multiplier.pipe” @NgModule ({ imports: [BrowserModule], declarations: [AppComponent, MultiplierPipe], bootstrap: [AppComponent] }) export class AppModule {} Following things need to be noted about the above code. We need to ensure to include our MultiplierPipe module. We also need to ensure it is included in the declarations section. Once you save all the code changes and refresh the browser, you will get the following output. Print Page Previous Next Advertisements ”;

Angular 2 – Transforming Data

Angular 2 – Transforming Data ”; Previous Next Angular 2 has a lot of filters and pipes that can be used to transform data. lowercase This is used to convert the input to all lowercase. Syntax Propertyvalue | lowercase Parameters None Result The property value will be converted to lowercase. Example First ensure the following code is present in the app.component.ts file. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { TutorialName: string = ”Angular JS2”; appList: string[] = [“Binding”, “Display”, “Services”]; } Next, ensure the following code is present in the app/app.component.html file. <div> The name of this Tutorial is {{TutorialName}}<br> The first Topic is {{appList[0] | lowercase}}<br> The second Topic is {{appList[1] | lowercase}}<br> The third Topic is {{appList[2]| lowercase}}<br> </div> Output Once you save all the code changes and refresh the browser, you will get the following output. uppercase This is used to convert the input to all uppercase. Syntax Propertyvalue | uppercase Parameters None. Result The property value will be converted to uppercase. Example First ensure the following code is present in the app.component.ts file. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { TutorialName: string = ”Angular JS2”; appList: string[] = [“Binding”, “Display”, “Services”]; } Next, ensure the following code is present in the app/app.component.html file. <div> The name of this Tutorial is {{TutorialName}}<br> The first Topic is {{appList[0] | uppercase }}<br> The second Topic is {{appList[1] | uppercase }}<br> The third Topic is {{appList[2]| uppercase }}<br> </div> Output Once you save all the code changes and refresh the browser, you will get the following output. slice This is used to slice a piece of data from the input string. Syntax Propertyvalue | slice:start:end Parameters start − This is the starting position from where the slice should start. end − This is the starting position from where the slice should end. Result The property value will be sliced based on the start and end positions. Example First ensure the following code is present in the app.component.ts file import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { TutorialName: string = ”Angular JS2”; appList: string[] = [“Binding”, “Display”, “Services”]; } Next, ensure the following code is present in the app/app.component.html file. <div> The name of this Tutorial is {{TutorialName}}<br> The first Topic is {{appList[0] | slice:1:2}}<br> The second Topic is {{appList[1] | slice:1:3}}<br> The third Topic is {{appList[2]| slice:2:3}}<br> </div> Output Once you save all the code changes and refresh the browser, you will get the following output. date This is used to convert the input string to date format. Syntax Propertyvalue | date:”dateformat” Parameters dateformat − This is the date format the input string should be converted to. Result The property value will be converted to date format. Example First ensure the following code is present in the app.component.ts file. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { newdate = new Date(2016, 3, 15); } Next, ensure the following code is present in the app/app.component.html file. <div> The date of this Tutorial is {{newdate | date:”MM/dd/yy”}}<br> </div> Output Once you save all the code changes and refresh the browser, you will get the following output. currency This is used to convert the input string to currency format. Syntax Propertyvalue | currency Parameters None. Result The property value will be converted to currency format. Example First ensure the following code is present in the app.component.ts file. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { newValue: number = 123; } Next, ensure the following code is present in the app/app.component.html file. <div> The currency of this Tutorial is {{newValue | currency}}<br> </div> Output Once you save all the code changes and refresh the browser, you will get the following output. percentage This is used to convert the input string to percentage format. Syntax Propertyvalue | percent Parameters None Result The property value will be converted to percentage format. Example First ensure the following code is present in the app.component.ts file. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { newValue: number = 30; } Next, ensure the following code is present in the app/app.component.html file. <div> The percentage is {{newValue | percent}}<br> </div> Output Once you save all the code changes and refresh the browser, you will get the following output. There is another variation of the percent pipe as follows. Syntax Propertyvalue | percent: ‘{minIntegerDigits}.{minFractionDigits}{maxFractionDigits}’ Parameters minIntegerDigits − This is the minimum number of Integer digits. minFractionDigits − This is the minimum number of fraction digits. maxFractionDigits − This is the maximum number of fraction digits. Result The property value will be converted to percentage format Example First ensure the following code is present in the app.component.ts file. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { newValue: number = 0.3; } Next, ensure the following code is present in the app/app.component.html file. <div> The percentage is {{newValue | percent:”2.2-5”}}<br> </div> Output Once you save all the code changes and refresh the browser, you will get the following output. Print Page Previous Next Advertisements ”;

Angular 2 – Advanced Configuration

Angular 2 – Advanced Configuration ”; Previous Next In this chapter, we will look at the other configuration files which are part of Angular 2 project. tsconfig.json This file is used to give the options about TypeScript used for the Angular JS project. { “compilerOptions”: { “target”: “es5”, “module”: “commonjs”, “moduleResolution”: “node”, “sourceMap”: true, “emitDecoratorMetadata”: true, “experimentalDecorators”: true, “lib”: [ “es2015”, “dom” ], “noImplicitAny”: true, “suppressImplicitAnyIndexErrors”: true } } Following are some key points to note about the above code. The target for the compilation is es5 and that is because most browsers can only understand ES5 typescript. The sourceMap option is used to generate Map files, which are useful when debugging. Hence, during development it is good to keep this option as true. The “emitDecoratorMetadata”: true and “experimentalDecorators”: true is required for Angular JS decorators. If not in place, Angular JS application will not compile. package.json This file contains information about Angular 2 project. Following are the typical settings in the file. { “name”: “angular-quickstart”, “version”: “1.0.0”, “description”: “QuickStart package.json from the documentation, supplemented with testing support”, “scripts”: { “build”: “tsc -p src/”, “build:watch”: “tsc -p src/ -w”, “build:e2e”: “tsc -p e2e/”, “serve”: “lite-server -c=bs-config.json”, “serve:e2e”: “lite-server -c=bs-config.e2e.json”, “prestart”: “npm run build”, “start”: “concurrently “npm run build:watch” “npm run serve””, “pree2e”: “npm run build:e2e”, “e2e”: “concurrently “npm run serve:e2e” “npm run protractor” –killothers –success first”, “preprotractor”: “webdriver-manager update”, “protractor”: “protractor protractor.config.js”, “pretest”: “npm run build”, “test”: “concurrently “npm run build:watch” “karma start karma.conf.js””, “pretest:once”: “npm run build”, “test:once”: “karma start karma.conf.js –single-run”, “lint”: “tslint ./src/**/*.ts -t verbose” }, “keywords”: [], “author”: “”, “license”: “MIT”, “dependencies”: { “@angular/common”: “~2.4.0”, “@angular/compiler”: “~2.4.0”, “@angular/core”: “~2.4.0”, “@angular/forms”: “~2.4.0”, “@angular/http”: “~2.4.0”, “@angular/platform-browser”: “~2.4.0”, “@angular/platform-browser-dynamic”: “~2.4.0”, “@angular/router”: “~3.4.0”, “angular-in-memory-web-api”: “~0.2.4”, “systemjs”: “0.19.40”, “core-js”: “^2.4.1”, “rxjs”: “5.0.1”, “zone.js”: “^0.7.4” }, “devDependencies”: { “concurrently”: “^3.2.0”, “lite-server”: “^2.2.2”, “typescript”: “~2.0.10”, “canonical-path”: “0.0.2”, “tslint”: “^3.15.1”, “lodash”: “^4.16.4”, “jasmine-core”: “~2.4.1”, “karma”: “^1.3.0”, “karma-chrome-launcher”: “^2.0.0”, “karma-cli”: “^1.0.1”, “karma-jasmine”: “^1.0.2”, “karma-jasmine-html-reporter”: “^0.2.2”, “protractor”: “~4.0.14”, “rimraf”: “^2.5.4”, “@types/node”: “^6.0.46”, “@types/jasmine”: “2.5.36” }, “repository”: {} } Some key points to note about the above code − There are two types of dependencies, first is the dependencies and then there are dev dependencies. The dev ones are required during the development process and the others are needed to run the application. The “build:watch”: “tsc -p src/ -w” command is used to compile the typescript in the background by looking for changes in the typescript files. systemjs.config.json This file contains the system files required for Angular JS application. This loads all the necessary script files without the need to add a script tag to the html pages. The typical files will have the following code. /** * System configuration for Angular samples * Adjust as necessary for your application needs. */ (function (global) { System.config ({ paths: { // paths serve as alias ”npm:”: ”node_modules/” }, // map tells the System loader where to look for things map: { // our app is within the app folder app: ”app”, // angular bundles ”@angular/core”: ”npm:@angular/core/bundles/core.umd.js”, ”@angular/common”: ”npm:@angular/common/bundles/common.umd.js”, ”@angular/compiler”: ”npm:@angular/compiler/bundles/compiler.umd.js”, ”@angular/platform-browser”: ”npm:@angular/platformbrowser/bundles/platform-browser.umd.js”, ”@angular/platform-browser-dynamic”: ”npm:@angular/platform-browserdynamic/bundles/platform-browser-dynamic.umd.js”, ”@angular/http”: ”npm:@angular/http/bundles/http.umd.js”, ”@angular/router”: ”npm:@angular/router/bundles/router.umd.js”, ”@angular/forms”: ”npm:@angular/forms/bundles/forms.umd.js”, // other libraries ”rxjs”: ”npm:rxjs”, ”angular-in-memory-web-api”: ”npm:angular-in-memory-web-api/bundles/inmemory-web-api.umd.js” }, // packages tells the System loader how to load when no filename and/or no extension packages: { app: { defaultExtension: ”js” }, rxjs: { defaultExtension: ”js” } } }); })(this); Some key points to note about the above code − ”npm:”: ”node_modules/” tells the location in our project where all the npm modules are located. The mapping of app: ”app” tells the folder where all our applications files are loaded. Print Page Previous Next Advertisements ”;

Angular 2 – Handling Events

Angular 2 – Handling Events ”; Previous Next In Angular 2, events such as button click or any other sort of events can also be handled very easily. The events get triggered from the html page and are sent across to Angular JS class for further processing. Let’s look at an example of how we can achieve event handling. In our example, we will look at displaying a click button and a status property. Initially, the status property will be true. When the button is clicked, the status property will then become false. Step 1 − 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 { Status: boolean = true; clicked(event) { this.Status = false; } } Following points need to be noted about the above code. We are defining a variable called status of the type Boolean which is initially true. Next, we are defining the clicked function which will be called whenever our button is clicked on our html page. In the function, we change the value of the Status property from true to false. Step 2 − Make the following changes to the app/app.component.html file, which is the template file. <div> {{Status}} <button (click) = “clicked()”>Click</button> </div> Following points need to be noted about the above code. We are first just displaying the value of the Status property of our class. Then are defining the button html tag with the value of Click. We then ensure that the click event of the button gets triggered to the clicked event in our class. Step 3 − Save all the code changes and refresh the browser, you will get the following output. Step 4 − Click the Click button, you will get the following output. Print Page Previous Next Advertisements ”;

Angular 2 – Data Display

Angular 2 – Data Display ”; Previous Next In Angular JS, it very easy to display the value of the properties of the class in the HTML form. Let’s take an example and understand more about Data Display. In our example, we will look at displaying the values of the various properties in our class in an HTML page. Step 1 − 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 { TutorialName: string = ”Angular JS2”; appList: string[] = [“Binding”, “Display”, “Services”]; } Following points need to be noted about the above code. We are defining an array called appList which of the type string. We are defining 3 string elements as part of the array which is Binding, Display, and Services. We have also defined a property called TutorialName which has a value of Angular 2. Step 2 − Make the following changes to the app/app.component.html file which is your template file. <div> The name of this Tutorial is {{TutorialName}}<br> The first Topic is {{appList[0]}}<br> The second Topic is {{appList[1]}}<br> The third Topic is {{appList[2]}}<br> </div> Following points need to be noted about the above code. We are referencing the TutorialName property to tell “what is the name of the tutorial in our HTML page”. We are using the index value for the array to display each of the 3 topics in our array. Step 3 − Save all the code changes and refresh the browser, you will get the below output. From the output, you can clearly see that the data is displayed as per the values of the properties in the class. Another simple example, which is binding on the fly is the use of the input html tag. It just displays the data as the data is being typed in the html tag. Make the following changes to the app/app.component.html file which is your template file. <div> <input [value] = “name” (input) = “name = $event.target.value”> {{name}} </div> Following points 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 − An expression exposed in event bindings by Angular, which has the value of the event’s payload. When you save all the code changes and refresh the browser, you will get the following output. Now, type something in the Input box such as “Tutorialspoint”. The output will change accordingly. Print Page Previous Next Advertisements ”;

CRUD Operations Using HTTP

Angular 2 – CRUD Operations Using HTTP ”; Previous Next The basic CRUD operation we will look into this chapter is the reading of data from a web service using Angular 2. Example In this example, we are going to define a data source which is a simple json file of products. Next, we are going to define a service which will be used to read the data from the json file. And then next, we will use this service in our main app.component.ts file. Step 1 − First let’s define our product.json file in Visual Studio code. In the products.json file, enter the following text. This will be the data which will be taken from the Angular JS application. [{ “ProductID”: 1, “ProductName”: “ProductA” }, { “ProductID”: 2, “ProductName”: “ProductB” }] Step 2 − Define an interface which will be the class definition to store the information from our products.json file. Create a file called products.ts. Step 3 − Insert the following code in the file. export interface IProduct { ProductID: number; ProductName: string; } The above interface has the definition for the ProductID and ProductName as properties for the interface. Step 4 − In the app.module.ts file include the following code − import { NgModule } from ”@angular/core”; import { BrowserModule } from ”@angular/platform-browser”; import { AppComponent } from ”./app.component”; import { HttpModule } from ”@angular/http”; @NgModule ({ imports: [ BrowserModule,HttpModule], declarations: [ AppComponent], bootstrap: [ AppComponent ] }) export class AppModule { } Step 5 − Define a products.service.ts file in Visual Studio code Step 6 − Insert the following code in the file. 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 { 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))); } } Following points need to be noted about the above program. The import {Http, Response} from ”@angular/http” statement is used to ensure that the http function can be used to get the data from the products.json file. The following statements are used to make use of the Reactive framework which can be used to create an Observable variable. The Observable framework is used to detect any changes in the http response which can then be sent back to the main application. import { Observable } from ”rxjs/Observable”; import ”rxjs/add/operator/map”; import ”rxjs/add/operator/do”; The statement private _producturl = ”app/products.json” in the class is used to specify the location of our data source. It can also specify the location of web service if required. Next, we define a variable of the type Http which will be used to get the response from the data source. Once we get the data from the data source, we then use the JSON.stringify(data) command to send the data to the console in the browser. Step 7 − Now in the app.component.ts file, place the following code. import { Component } from ”@angular/core”; import { IProduct } from ”./product”; import { ProductService } from ”./products.service”; import { appService } from ”./app.service”; import { Http , Response } from ”@angular/http”; import { Observable } from ”rxjs/Observable”; import ”rxjs/add/operator/map”; @Component ({ selector: ”my-app”, template: ”<div>Hello</div>”, providers: [ProductService] }) export class AppComponent { iproducts: IProduct[]; constructor(private _product: ProductService) { } ngOnInit() : void { this._product.getproducts() .subscribe(iproducts => this.iproducts = iproducts); } } Here, the main thing in the code is the subscribe option which is used to listen to the Observable getproducts() function to listen for data from the data source. Now save all the codes and run the application using npm. Go to the browser, we will see the following output. In the Console, we will see the data being retrieved from products.json file. Print Page Previous Next Advertisements ”;

Angular 2 – Dependency Injection

Angular 2 – Dependency Injection ”; Previous Next Dependency injection is the ability to add the functionality of components at runtime. Let’s take a look at an example and the steps used to implement dependency injection. Step 1 − Create a separate class which has the injectable decorator. The injectable decorator allows the functionality of this class to be injected and used in any Angular JS module. @Injectable() export class classname { } Step 2 − Next in your appComponent module or the module in which you want to use the service, you need to define it as a provider in the @Component decorator. @Component ({ providers : [classname] }) Let’s look at an example on how to achieve this. Step 1 − Create a ts file for the service called app.service.ts. Step 2 − Place the following code in the file created above. import { Injectable } from ”@angular/core”; @Injectable() export class appService { getApp(): string { return “Hello world”; } } The following points need to be noted about the above program. The Injectable decorator is imported from the angular/core module. We are creating a class called appService that is decorated with the Injectable decorator. We are creating a simple function called getApp which returns a simple string called “Hello world”. Step 3 − In the app.component.ts file place the following code. import { Component } from ”@angular/core”; import { appService } from ”./app.service”; @Component({ selector: ”my-app”, template: ”<div>{{value}}</div>”, providers: [appService] }) export class AppComponent { value: string = “”; constructor(private _appService: appService) { } ngOnInit(): void { this.value = this._appService.getApp(); } } The following points need to be noted about the above program. First, we are importing our appService module in the appComponent module. Then, we are registering the service as a provider in this module. In the constructor, we define a variable called _appService of the type appService so that it can be called anywhere in the appComponent module. As an example, in the ngOnInit lifecyclehook, we called the getApp function of the service and assigned the output to the value property of the AppComponent class. Save all the code changes and refresh the browser, you will get the following output. Print Page Previous Next Advertisements ”;

Angular 2 – Quick Guide

Angular 2 – Quick Guide ”; Previous Next Angular 2 – Overview 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. Angular 2 – Environment To start working with Angular 2, you need to get the following key components installed. Npm − This is known as the node package manager that is used to work with the open source repositories. Angular JS as a framework has dependencies on other components. And npm can be used to download these dependencies and attach them to your project. Git − This is the source code software that can be used to get the sample application from the github angular site. Editor − There are many editors that can be used for Angular JS development such as Visual Studio code and WebStorm. In our tutorial, we will use Visual Studio code which comes free of cost from Microsoft. npm Installation Let’s now look at the steps to get npm installed. The official site for npm is https://www.npmjs.com/ Step 1 − Go to the “get started with npm” section in the site. Step 2 − In the next screen, choose the installer to download, depending on the operating system. For the purpose of this exercise, download the Windows 64 bit version. Step 3 − Launch the installer. In the initial screen, click the Next button. Step 4 − In the next screen, Accept the license agreement and click the next button. Step 5 − In the next screen, choose the destination folder for the installation and click the Next button. Step 6 − Choose the components in the next screen and click the Next button. You can accept all the components for the default installation. Step 7 − In the next screen, click the Install button. Step 8 − Once the installation is complete, click the Finish button. Step 9 − To confirm the installation, in the command prompt you can issue the command npm version. You will get the version number of npm as shown in the following screenshot. Installation of Visual Studio Code Following are the features of Visual Studio Code − Light editor when compared to the actual version of Visual Studio. Can be used for coding languages such as Clojure, Java, Objective-C and many other languages. Built-in Git extension. Built-in IntelliSense feature. Many more extensions for development. The official site for Visual Studio code is https://code.visualstudio.com/ Step 1 − After the download is complete, please follow the installation steps. In the initial screen, click the Next button. Step 2 − In the next screen, accept the license agreement and click the Next button. Step 3 − In the next screen, choose the destination location for the installation and click the next button. Step 4 − Choose the name of the program shortcut and click the Next button. Step 5 − Accept the default settings and click the Next button. Step 6 − Click the Install button in the next screen. Step 7 − In the final screen, click the Finish button to launch Visual Studio Code. Installing Git Some of the key features of Git are − Easy branching and merging of code. Provision to use many techniques for the flow of code within Git. Git is very fast when compared with other SCM tools. Offers better data assurance. Free and open source. The official site for Git is https://git-scm.com/ Step 1 − After the download is complete, please follow the installation steps. In the initial screen, click the Next button. Step 2 − Choose the components which needs to be installed. You can accept the default components. Step 3 − In the next step, choose the program shortcut name and click the Next button. Step 4 − Accept the default SSH executable and click the Next button. Step 5 − Accept the default setting of “Checkout Windows style, commit Unix style endings” and click the Next button. Step 6 − Now, accept the default setting of the terminal emulator and click the Next button. Step 7 − Accept the default settings

Angular 2 – Questions and Answers

Angular 2 – Questions and Answers ”; Previous Next Angular 2 Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 Angular 2 Interview Questions This section provides a huge collection of Angularjs Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 Angular 2 Online Quiz This section provides a great collection of Angularjs Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 Angular 2 Online Test If you are preparing to appear for a Java and Angularjs Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 Angular 2 Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;

Angular 2 – Routing

Angular 2 – Routing ”; Previous Next Routing helps in directing users to different pages based on the option they choose on the main page. Hence, based on the option they choose, the required Angular Component will be rendered to the user. Let’s see the necessary steps to see how we can implement routing in an Angular 2 application. Step 1 − Add the base reference tag in the index.html file. <!DOCTYPE html> <html> <head> <base href = “/”> <title>Angular QuickStart</title> <meta charset = “UTF-8”> <meta name = “viewport” content = “width = device-width, initial-scale = 1”> <base href = “/”> <link rel = “stylesheet” href = “styles.css”> <!– Polyfill(s) for older browsers –> <script src = “node_modules/core-js/client/shim.min.js”></script> <script src = “node_modules/zone.js/dist/zone.js”></script> <script src = “node_modules/systemjs/dist/system.src.js”></script> <script src = “systemjs.config.js”></script> <script> System.import(”main.js”).catch(function(err){ console.error(err); }); </script> </head> <body> <my-app></my-app> </body> </html> Step 2 − Create two routes for the application. For this, create 2 files called Inventory.component.ts and product.component.ts Step 3 − Place the following code in the product.component.ts file. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: ”Products”, }) export class Appproduct { } Step 4 − Place the following code in the Inventory.component.ts file. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: ”Inventory”, }) export class AppInventory { } Both of the components don’t do anything fancy, they just render the keywords based on the component. So for the Inventory component, it will display the Inventory keyword to the user. And for the products component, it will display the product keyword to the user. Step 5 − In the app.module.ts file, add the following code − import { NgModule } from ”@angular/core”; import { BrowserModule } from ”@angular/platform-browser”; import { AppComponent } from ”./app.component”; import { Appproduct } from ”./product.component”; import { AppInventory } from ”./Inventory.component”; import { RouterModule, Routes } from ”@angular/router”; const appRoutes: Routes = [ { path: ”Product”, component: Appproduct }, { path: ”Inventory”, component: AppInventory }, ]; @NgModule ({ imports: [ BrowserModule, RouterModule.forRoot(appRoutes)], declarations: [ AppComponent,Appproduct,AppInventory], bootstrap: [ AppComponent ] }) export class AppModule { } The following points need to be noted about the above program − The appRoutes contain 2 routes, one is the Appproduct component and the other is the AppInventory component. Ensure to declare both of the components. The RouterModule.forRoot ensures to add the routes to the application. Step 6 − In the app.component.ts file, add the following code. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: ` <ul> <li><a [routerLink] = “[”/Product”]”>Product</a></li> <li><a [routerLink] = “[”/Inventory”]”>Inventory</a></li> </ul> <router-outlet></router-outlet>` }) export class AppComponent { } The following point needs to be noted about the above program − <router-outlet></router-outlet> is the placeholder to render the component based on which option the user chooses. Now, save all the code and run the application using npm. Go to the browser, you will see the following output. Now if you click the Inventory link, you will get the following output. Adding an Error Route In Routing, one can also add an error route. This can happen if the user goes to a page which does not exist in the application. Let’s see how we can go about implementing this. Step 1 − Add a PageNotFound component as NotFound.component.ts as shown below − Step 2 − Add the following code to the new file. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: ”Not Found”, }) export class PageNotFoundComponent { } Step 3 − Add the following code to the app.module.ts file. import { NgModule } from ”@angular/core”; import { BrowserModule } from ”@angular/platform-browser”; import { AppComponent } from ”./app.component”; import { Appproduct } from ”./product.component” import { AppInventory } from ”./Inventory.component” import { PageNotFoundComponent } from ”./NotFound.component” import { RouterModule, Routes } from ”@angular/router”; const appRoutes: Routes = [ { path: ”Product”, component: Appproduct }, { path: ”Inventory”, component: AppInventory }, { path: ”**”, component: PageNotFoundComponent } ]; @NgModule ({ imports: [ BrowserModule, RouterModule.forRoot(appRoutes)], declarations: [ AppComponent,Appproduct,AppInventory,PageNotFoundComponent], bootstrap: [ AppComponent ] }) export class AppModule { } The following point needs to be noted about the above program − Now we have an extra route called path: ”**”, component: PageNotFoundComponent. Hence, ** is for any route which does not fit the default route. They will be directed to the PageNotFoundComponent component. Now, save all the code and run the application using npm. Go to your browser, and you will see the following output. Now, when you go to any wrong link you will get the following output. Print Page Previous Next Advertisements ”;