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 ”;

Angular 2 – Directives

Angular 2 – Directives ”; Previous Next A directive is a custom HTML element that is used to extend the power of HTML. Angular 2 has the following directives that get called as part of the BrowserModule module. ngif ngFor If you view the app.module.ts file, you will see the following code and the BrowserModule module defined. By defining this module, you will have access to the 2 directives. 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 { } Now let’s look at each directive in detail. ngIf The ngif element is used to add elements to the HTML code if it evaluates to true, else it will not add the elements to the HTML code. Syntax *ngIf = ”expression” If the expression evaluates to true then the corresponding gets added, else the elements are not added. Let’s now take a look at an example of how we can use the *ngif directive. Step 1 − First add a property to the class named appStatus. This will be of type Boolean. Let’s keep this value as true. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { appTitle: string = ”Welcome”; appStatus: boolean = true; } Step 2 − Now in the app.component.html file, add the following code. <div *ngIf = ”appStatus”>{{appTitle}} Tutorialspoint </div> In the above code, we now have the *ngIf directive. In the directive we are evaluating the value of the appStatus property. Since the value of the property should evaluate to true, it means the div tag should be displayed in the browser. Once we add the above code, we will get the following output in the browser. Output ngFor The ngFor element is used to elements based on the condition of the For loop. Syntax *ngFor = ”let variable of variablelist” The variable is a temporary variable to display the values in the variablelist. Let’s now take a look at an example of how we can use the *ngFor directive. Step 1 − First add a property to the class named appList. This will be of the type which can be used to define any type of arrays. 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” }, { “ID”: “2”, “Name” : “Two” } ]; } Hence, we are defining the appList as an array which has 2 elements. Each element has 2 sub properties as ID and Name. Step 2 − In the app.component.html, define the following code. <div *ngFor = ”let lst of appList”> <ul> <li>{{lst.ID}}</li> <li>{{lst.Name}}</li> </ul> </div> In the above code, we are now using the ngFor directive to iterate through the appList array. We then define a list where each list item is the ID and name parameter of the array. Once we add the above code, we will get the following output in the browser. Output Print Page Previous Next Advertisements ”;

Angular 2 – Forms

Angular 2 – Forms ”; Previous Next Angular 2 can also design forms which can use two-way binding using the ngModel directive. Let’s see how we can achieve this. Step 1 − Create a model which is a products model. Create a file called products.ts file. Step 2 − Place the following code in the file. export class Product { constructor ( public productid: number, public productname: string ) { } } This is a simple class which has 2 properties, productid and productname. Step 3 − Create a product form component called product-form.component.ts component and add the following code − import { Component } from ”@angular/core”; import { Product } from ”./products”; @Component ({ selector: ”product-form”, templateUrl: ”./product-form.component.html” }) export class ProductFormComponent { model = new Product(1,”ProductA”); } The following points need to be noted about the above program. Create an object of the Product class and add values to the productid and productname. Use the templateUrl to specify the location of our product-form.component.html which will render the component. Step 4 − Create the actual form. Create a file called product-form.component.html and place the following code. <div class = “container”> <h1>Product Form</h1> <form> <div class = “form-group”> <label for = “productid”>ID</label> <input type = “text” class = “form-control” id = “productid” required [(ngModel)] = “model.productid” name = “id”> </div> <div class = “form-group”> <label for = “name”>Name</label> <input type = “text” class = “form-control” id = “name” [(ngModel)] = “model.productname” name = “name”> </div> </form> </div> The following point needs to be noted about the above program. The ngModel directive is used to bind the object of the product to the separate elements on the form. Step 5 − Place the following code in the app.component.ts file. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: ”<product-form></product-form>” }) export class AppComponent { } Step 6 − Place the below code in the app.module.ts file import { NgModule } from ”@angular/core”; import { BrowserModule } from ”@angular/platform-browser”; import { AppComponent } from ”./app.component”; import { FormsModule } from ”@angular/forms”; import { ProductFormComponent } from ”./product-form.component”; @NgModule ({ imports: [ BrowserModule,FormsModule], declarations: [ AppComponent,ProductFormComponent], bootstrap: [ AppComponent ] }) export class AppModule { } Step 7 − Save all the code and run the application using npm. Go to your browser, you will see the following output. Print Page Previous Next Advertisements ”;

Angular 2 – Nested Containers

Angular 2 – Nested Containers ”; Previous Next In Angular JS, it is possible to nest containers inside each other. The outside container is known as the parent container and the inner one is known as the child container. Let’s look at an example on how to achieve this. Following are the steps. Step 1 − Create a ts file for the child container called child.component.ts. Step 2 − In the file created in the above step, place the following code. import { Component } from ”@angular/core”; @Component ({ selector: ”child-app”, template: ”<div> {{values}} </div> ” }) export class ChildComponent { values = ””; ngOnInit() { this.values = “Hello”; } } The above code sets the value of the parameter this.values to “Hello”. Step 3 − In the app.component.ts file, place the following code. import { Component } from ”@angular/core”; import { ChildComponent } from ”./child.component”; @Component ({ selector: ”my-app”, template: ”<child-app></child-app> ” }) export class AppComponent { } In the above code, notice that we are now calling the import statement to import the child.component module. Also we are calling the <child-app> selector from the child component to our main component. Step 4 − Next, we need to ensure the child component is also included 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” import { ChildComponent } from ”./child.component”; @NgModule ({ imports: [BrowserModule], declarations: [AppComponent, MultiplierPipe, ChildComponent], bootstrap: [AppComponent] }) export class AppModule {} Once you save all the code changes and refresh the browser, you will get the following output. Print Page Previous Next Advertisements ”;

Angular 2 – Architecture

Angular 2 – Architecture ”; Previous Next The following screenshot shows the anatomy of an Angular 2 application. Each application consists of Components. Each component is a logical boundary of functionality for the application. You need to have layered services, which are used to share the functionality across components. Following is the anatomy of a Component. A component consists of − Class − This is like a C++ or Java class which consists of properties and methods. Metadata − This is used to decorate the class and extend the functionality of the class. Template − This is used to define the HTML view which is displayed in the application. Following is an example of a component. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { appTitle: string = ”Welcome”; } Each application is made up of modules. Each Angular 2 application needs to have one Angular Root Module. Each Angular Root module can then have multiple components to separate the functionality. Following is an example of a root module. 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 { } Each application is made up of feature modules where each module has a separate feature of the application. Each Angular feature module can then have multiple components to separate the functionality. Print Page Previous Next Advertisements ”;

Angular 2 – Lifecycle Hooks

Angular 2 – Lifecycle Hooks ”; Previous Next Angular 2 application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application. The following diagram shows the entire processes in the lifecycle of the Angular 2 application. Following is a description of each lifecycle hook. ngOnChanges − When the value of a data bound property changes, then this method is called. ngOnInit − This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens. ngDoCheck − This is for the detection and to act on changes that Angular can”t or won”t detect on its own. ngAfterContentInit − This is called in response after Angular projects external content into the component”s view. ngAfterContentChecked − This is called in response after Angular checks the content projected into the component. ngAfterViewInit − This is called in response after Angular initializes the component”s views and child views. ngAfterViewChecked − This is called in response after Angular checks the component”s views and child views. ngOnDestroy − This is the cleanup phase just before Angular destroys the directive/component. Following is an example of implementing one lifecycle hook. In the app.component.ts file, place the following code. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, template: ”<div> {{values}} </div> ” }) export class AppComponent { values = ””; ngOnInit() { this.values = “Hello”; } } In the above program, we are calling the ngOnInit lifecycle hook to specifically mention that the value of the this.values parameter should be set to “Hello”. Once you save all the code changes and refresh the browser, you will get the following output. Print Page Previous Next Advertisements ”;

Angular 2 – Discussion

Discuss Angular 2 ”; Previous Next 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. Print Page Previous Next Advertisements ”;

Angular 2 – Environment

Angular 2 – Environment ”; Previous Next 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 and click the Next button. Step 8 − You can skip the experimental options and click the Install button. Step 9 − In the final screen, click the Finish button to complete the installation. Print Page Previous Next Advertisements ”;

Angular 2 – Useful Resources

Angular 2 – Useful Resources ”; Previous Next The following resources contain additional information on Angular 2. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Angular – The Complete Course 14 Lectures 48 mins Ganesh Kavhar More Detail Angular JS Full Stack: Create and Host Listing/Classified Site 59 Lectures 4 hours Jay R More Detail Full-Stack web app development with Angular 12, .NET Core Web API & Mongo DB Most Popular 20 Lectures 49 mins Vinay Kumar More Detail Angular 12, .NET Core Web API & Microsoft SQL Full Stack Web Development 21 Lectures 55 mins Vinay Kumar More Detail Angular 12, .NET Core Web API and MySQL Web Development 21 Lectures 51 mins Vinay Kumar More Detail Angular 12, .NET Core Web API & PostgreSQL Full Stack Web Development 5 Lectures 51 mins Vinay Kumar More Detail Print Page Previous Next Advertisements ”;

Angular 2 – Templates

Angular 2 – Templates ”; Previous Next In the chapter on Components, we have already seen an example of the following template. template: ” <div> <h1>{{appTitle}}</h1> <div>To Tutorials Point</div> </div> ” This is known as an inline template. There are other ways to define a template and that can be done via the templateURL command. The simplest way to use this in the component is as follows. Syntax templateURL: viewname.component.html Parameters viewname − This is the name of the app component module. After the viewname, the component needs to be added to the file name. Following are the steps to define an inline template. Step 1 − Create a file called app.component.html. This will contain the html code for the view. Step 2 − Add the following code in the above created file. <div>{{appTitle}} Tutorialspoint </div> This defines a simple div tag and references the appTitle property from the app.component class. Step 3 − In the app.component.ts file, add the following code. import { Component } from ”@angular/core”; @Component ({ selector: ”my-app”, templateUrl: ”app/app.component.html” }) export class AppComponent { appTitle: string = ”Welcome”; } From the above code, the only change that can be noted is from the templateURL, which gives the link to the app.component.html file which is located in the app folder. Step 4 − Run the code in the browser, you will get the following output. From the output, it can be seen that the template file (app.component.html) file is being called accordingly. Print Page Previous Next Advertisements ”;