angular 5 [ n g ]angular recommends the use of microsoft's typescript language, which...

68
Angular 5 [ng] INTRODUCTION: Angular is a TypeScript-based open-source front-end web application platform led by the Angular Team at Google and by a community of individuals and corporations. Angular is a complete rewrite from the same team that built AngularJS. AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0. Difference between angular.js and angular: Angular was a ground-up rewrite of AngularJS. Angular does not have a concept of "scope" or controllers, instead it uses a hierarchy of components as its primary architectural characteristic. Angular has a different expression syntax, focusing on "[ ]" for property binding, and "( )" for event binding. Modularity – much core functionality has moved to modules. Angular recommends the use of Microsoft's TypeScript language, which introduces the following features: Class-based Object Oriented Programming. Static Typing Generics TypeScript is a superset of ECMAScript 6 (ES6), and is backwards compatible with ECMAScript 5 (i.e.: JavaScript). Angular also includes ES6: Lambdas Iterators For/Of loops Reflection Dynamic loading 1

Upload: others

Post on 23-May-2020

13 views

Category:

Documents


0 download

TRANSCRIPT

Angular 5 [ng]  

INTRODUCTION:  

● Angular is a TypeScript-based open-source front-end web application platform led by the Angular Team at Google and by a community of individuals and corporations. 

● Angular is a complete rewrite from the same team that built AngularJS. ● AngularJS is a very powerful JavaScript Framework. It is used in Single Page 

Application (SPA) projects. ● It extends HTML DOM with additional attributes and makes it more responsive to 

user actions.  ● AngularJS is open source, completely free, and used by thousands of developers 

around the world. It is licensed under the Apache license version 2.0.  

 Difference between angular.js and angular:  Angular was a ground-up rewrite of AngularJS.  

➔ Angular does not have a concept of "scope" or controllers, instead it uses a hierarchy of components as its primary architectural characteristic. 

➔ Angular has a different expression syntax, focusing on "[ ]" for property binding, and "( )" for event binding. 

➔ Modularity – much core functionality has moved to modules. ➔ Angular recommends the use of Microsoft's TypeScript language, which 

introduces the following features: ◆ Class-based Object Oriented Programming. ◆ Static Typing ◆ Generics 

➔ TypeScript is a superset of ECMAScript 6 (ES6), and is backwards compatible with ECMAScript 5 (i.e.: JavaScript). Angular also includes ES6: 

➔ Lambdas ➔ Iterators ➔ For/Of loops ➔ Reflection 

➔ Dynamic loading  

  

1

Various versions of Angular:  

● Angular 2.0.0 (sep 2016) ● Angular 4.0.0 (mar 2017) ● Angular 5.0.0 (nov 2017) ● Angualr 6.0.0 (may 2018) 

 Creating Tiles Cart App:  

● First create a tiles cart app by using the command, ng new tilescart in the node prompt. 

 

   

● After creating the tiles cart app, Create the tiles component to show the properties of that component. 

  COMPONENT:  

● Components are the fundamental building block of Angular applications. ● Components are composable, we can build larger Components from smaller ones. ● An Angular application is therefore just a tree of such Components, when each 

Component renders, it recursively renders its children Components. ● At the root of that tree is the top level Component, the root Component. 

     

2

Creating tiles component:  

● For creating the tiles component, use the command ng generate component tiles.  

  

● In the explorer window you can see the tiles component is created within the app component. 

● Here in the tiles component, the files like .html, .css and .ts files are generated automatically because of the angular cli.  

     

3

In the tiles.component.html file, type as,

<thead> <tr> <th>IMAGES</th> <th>TNAME</th> <th>PRICE</th> <th>TYPE</th> <th>COLOR</th> <th>MODEL</th> <th>status</th> </tr> </thead> <tbody> <tr> <td> <img [src] = "imagePath + tile.image" style = "height:75px; width:75px" alt=" "></td> <td>{{tile.name }}</td> <td>{{tile.price }}</td> <td>{{tile.type }}</td> <td>{{tile.color}}</span></td> <td>{{tile.model}}</td> <td>{{tile.status}}</td> </tr></tbody>

● In tiles.component.ts file, types as  

export class TileService { tiles:Array<ITile> =[{ "image":"tilegrey.jpg", "name":"johnson tiles", "price":4000, "type": "ceramic tiles", "color": "faded grey", "model": "s-676", "status": 0 }, { "image":"bblack.jpg", "name":"R.V tiles", "price":2500, "type": "floor tiles", "color": "blue black", "model": "zs-1404", "status": 1 },]; 

 

4

● Run your file using the command, ng serve -- open to start the local server. ● Then the output will be displayed in the browser as follows, 

  

   Directives:  

● AngularJS directives are extended HTML attributes with the prefix ng- ● Directive decorator allows you to mark a class as an Angular directive and provide 

additional metadata that determines how the directive should be processed, instantiated and used at runtime. 

● Directives allow you to attach behavior to elements in the DOM. ● A directive must belong to an NgModule in order for it to be usable by another 

directive, component, or application.  ● To specify that a directive is a member of an NgModule, you should list it in the 

declarations field of that NgModule.  Structural directives:  

➔ Structural directives are responsible for HTML layout.  ➔ They shape or reshape the DOM's structure, typically by adding, removing, or                       

manipulating elements. ➔ Structural directives are easy to recognize. An asterisk (*) precedes the directive                       

attribute name. ➔ The * syntax is used as a shortcut for creating template tags. ➔ The * ngIf structural directive will remove or show an element based on whether the                             

variable it is bound to evaluates to true or false. ➔ The * ngFor structural directive will loop over an array of data and create a DOM                               

element for each element in the array, stamping it with the specific values for each                             array element.  

5

 Looping in Angular5: 

 ● Here we use the array objects to show the properties of the tiles component. ● We can loop through the items in angular by using the ngFor directive,  

 

<tbody> <tr *ngFor ="let tile of filteredTiles" app-tile [tile] = 'tile'> <td> <img [src] = "imagePath + tile.image" style = "height:75px; width:75px" alt=" "> --> </td>

<td>{{tile.name }}</td> <td>{{tile.price }}</td> <td>{{tile.type }}</td> <td>{{tile.color}}</span></td> <td>{{tile.model}}</td> <td>{{tile.status}}</td> </tr></tbody>

 

  

● Use the ngIf direcctive to check whether the tiles component can consists of values                           >0. You can set any condition to your component by using ngIf.   

<table *ngIf = "tiles && tiles.length > 0" class="table"> <thead> <tr>

<th>IMAGES</th> <th>TNAME</th> <th>PRICE</th> <th>TYPE</th> <th>COLOR</th> <th>MODEL</th> <th>status</th>

</tr> </thead>

 

      

6

● Now, when you try to run the program. The program will run like,  

  

 ngFor:  

● NgFor is a structural directive, meaning that it changes the structure of the DOM. ● It’s point is to repeat a given HTML template once for each value in an array, each                                 

time passing it the array value as context for string interpolation or binding. ● This directive is the successor of Angular1s ng-repeat directive. 

 Syntax:  

*ngFor="let <value> of <collection>".  

● <value> is a variable name of your choosing. ● <collection> is a property on your component which holds a collection, usually an                         

array but anything that can be iterated over in a for-of loop.  ngIf:  

● The ngIf directive is used when you want to display or remove an element based on                               a condition. 

● If the condition is false the element the directive is attached to will be removed from                               the DOM. 

● We define the condition by passing an expression to the directive which is evaluated                           in the context of it’s host component. 

   

7

Syntax:  

 *ngIf="<condition>"  

Note: The difference between [hidden]='false' and *ngIf='false' is that the first method                       simply hides the element. The second method with ngIf removes the element completely                         from the DOM.  

DATA BINDING:  

➢ Data Binding is a process that creates a connection between the application’s UI and                           the data. 

➢ When the data changes its value, the UI elements that are bound to the data, will also                                 change.  

➢ Angular handles data binding by synchronizing the state of the view, with the data in                             the component. 

➢ The following types of bindings are supported by Angular:  

● Interpolation ● Property Binding ● Event Binding ● Two-way binding 

 Interpolation (or) one way binding:  

● Interpolation binds the data one-way. This means that when value of the field bound                           using interpolation changes, it is updated in the page as well.  

● It cannot change the value of the field. An object of the component class is used as                                 data context for the template of the component.  

● So the value to be bound on the view has to be assigned to a field in the component                                     class. 

  Component --------- {{ value }} ------> DOM  Property Binding:  

● In property binding, we bind a property of a DOM element. ● Property binding in Angular 5 is one-way, in that communication goes from the                         

component class to the template. ● If these fields to the component are changed then Angular will update the DOM, but                             

any changes in the DOM are not reflected back in the component. 

8

Example:  

★ <img [src] = " imageofjs "> ★ <img bind - src = " imgofangular "> 

 ● Adding bind- before the element property also achieves the same thing. 

  Property binding in tilescart:  

● Here we will add image files to our tilescart with the help of property binding. ● For that first add the img src to our tilescart.html file to diplay the images in DOM. 

 

<td> <img [src] = "imagePath + tile.image" style = "height:75px; width:75px" alt=" ">

</td> <td>{{tile.tname }}</td> <td>{{tile.price }}</td> <td>{{tile.type }}</td>

● Here, you can see [src] instead of src. The src refers to the normal html                             attribute.whereas, [src] refers to the property binding.  

● Give the image path and define its type. In the array object set the property as image                                 and the property name.  

imagePath:string = "/assets/images/"; tiles : any[] =[{ "image":"tilegrey.jpg", "tname":"johnson tiles", "price":"4000", "type": "ceramic tiles", "color": "faded grey", "tmodel": "s-676", "status": 0 }];

   

9

● Run the tilescart app and the output will display like as follows,  

  

● Displaying our table by using nth-child.  

        

10

Using bootstrap in angular:  

● Use bootstrap in our angular app to display the template more attractive. ● For that, first we need to install the bootstrap in our system. ● Use the command as, npm install bootsrap @ 3.3.7 --save in the node prompt. ● If you give like npm install bootstrap means it will install the latest version of                             

bootstrap. Here we are using the version 3.3.7 for our consistency. ● In our command we didn’t used the -g. Because, we are not downloading the                           

bootstrap globally instead we will use it only in our own application.  

  ● You can see the bootstrap.css file in the specified location as follows, 

 

  ● Copy and paste the path into the angular.json file which is available in your                           

application.  

● In the styles dependency you can paste the path of the bootstrap.css file.  

 

11

● After adding the bootstrap file in your application, your application will look like, 

  

Two-way binding:  ● The feature two-way binding in Angular is derived from the property and event                         

bindings.  ● The property and event bindings are directed one way with the former receiving data                           

into view from the component object and the later sending data from the view to the                               component.  

● The two-way binding is a combination of these two bindings; it gets the data from the                               component object to the view and sets the data from view to the component object.  

❖ The following snippet shows an example of a directive, ngModel to show how                         two-way binding can be used:  <input [ ( ngMode ) ] = " username " > <p> show name {{ username }} </p> 

 ❖ Angular allows the shorthand syntax using [()], also called “Banana in a box”.                         

So after all, it’s really an implementation detail of ngModel that enables                       two-way data binding. 

 What [(ngModel)] do behind?  

● Two-way binding combines the input and output binding into a single notation using                         the ngmodel directive. 

● For instance, <input [(ngModel)] = “name”> ● What this is doing behind is equivalent to: ● <input [ngmodel] = “name” (ngmodelchange) = “name”> 

 

12

Two way binding in tiles cart application:  

● We use two way binding typically with the input controls. ● Here, we use forms module to work with the two way binding. 

 ➢ For that, first we need to import the forms mdule. Before that we just used the core                                 

modules within our application.  ➢ Go to the app.module.ts file and import the forms module as angular module. 

 

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

➢ Import the forms module as ngModule . 

@NgModule({ declarations: [ AppComponent, TilesComponent, LoginComponent, ], imports: [ BrowserModule,FormsModule]

➢ Go to the login.component.html file and design the form,  

<div class = "form-group"> <label for="Username">Username</label>&nbsp; &nbsp; <input type="text" name="Username" id="Username" [(ngModel)] = "Username"/> </div> <div> <label for="password">Password</label>&nbsp;&nbsp;&nbsp; <input type="password" name="password" id="password"/> </div> <div> <button class ="btn btn-primary" (click) = "login()"> Submit </button></div>

<div>Modified user name is {{ Username }}</div>

➢ You can specify whichever field that you want. you can give it as [(ngModel)] =                             “fieldname“. 

13

 ➢ While running our application you can see the modified user name below. It was two                             

way, as it get the user input as one way and display the output in another way.  

  

Event Binding:  

● When a user interacts with your application, it is sometimes necessary to know when                           this happens.  

● A click, hover, or a keyboard action are all events that you can use to call component                                 logic within Angular. 

● That's what Angular event binding is all about. It is a one-way data binding, in that it                                 sends information from the view to the component class. 

● This is opposite from property binding, where data is sent from the component                           class to the view. 

 Example:  

< button (click) = " login( ) " >     

➔ Go to the login.component.html file and type as  

14

 

<div><button class ="btn btn-primary" (click) = "login()"> Submit</button></div> 

 ➔ Go to the login.component.ts file and type as, 

 

export class LoginComponent implements OnInit { username : string =" "; password : string =" "; users : string[] = ["john", "andy", "morri", "linda", "roy"]; constructor() { } ngOnInit() { } login(){ if (this.username == null || this.username == " " ) { console.log('user name required'); } else if(!this.users.includes(this.username)) {

console.log(`user ${this.username} is not a registerd user`); }}}

➔ The output will be generated as follows, 

 

   ➔ In the browser console the output is shown like, 

 

15

   

PIPES :  ● Pipes are used to transform data, when we only need that data transformed in a                             

template. ● If we need the data transformed generally we would implement it in our model. ● We could convert the number into a string and store that string in the model but if                                 

the only place we want to show that number is in a view we can use a pipe instead. ● We use a pipe with the | syntax in the template, the | character is called the pipe                                   

character. ● Pipes are there in Angular from Angular v2 onwards. ● There are many inbuilt pipes available in Angular 5 and it gives an easy template to                               

create your own pipe using @angular/cli. ● Pipes are just like filters in Angular 1 

 Built-in Pipes:  

❖ Angular comes with a stock of pipes such as DatePipe, UpperCasePipe,                     LowerCasePipe, CurrencyPipe, and PercentPipe.  

❖ They are all available for use in any template. ❖ Built-in pipes are completely provided by the angular. 

 ● Go to the tiles.component.html, and add the pipes to the required fields. 

 

<td>{{tile.tname | uppercase}}</td> <td>{{tile.price | currency:'USD':true}}</td> <td>{{tile.type | titlecase }}</td>

    

● Though there are the built-in pipes, they can run directly.  

16

  Custom pipes: 

 ● If we want to transform the data from the data from to another from which are not                                 

available out of the box in angular we are going to use the custom filter. ● For instance, we have status which contains 0 or 1 but in the UI we want to display it                                     

as InStock or Out of the Stock we are going to use the custom pipes.  

● Creae your own pipe.ts file in your application as follows,  

  

● In the pipe.ts file write the code to set the function or condition to that pipe, 

import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'status' }) export class StatusPipe implements PipeTransform { transform(value: any, args?: any): any { if (value == 1){ return "In Stock"; } else { return "Not In Stock"; }

17

} }

● In the tiles.component.html file, give the pipe name as ‘status’ as what given in                           pipe.ts file. 

 

<td>{{tile.status | status}}</td>

● The pipe is applied to the status field to show whether the given item is in stock or                                   out of the stock.  

             

● To display the table’s odd and even rows to appear in different colors. For that, use                               the tr : nth child (odd or even) in the tiles.component.css file. 

18

 

   FILTERS: 

 ● Filters are basically used to filter an item from a group of items, which are there in an                                   

array or an object array.  ● It selects a subset of the items from an array and returns it as a new array and this                                     

item is displayed on UI. ● Filter is not a function after upgrading to angular 5 

 Filters in our tiles cart application:  

● In our tiles cart application, we are going to filter the items like name, price, model. ● For that, first add the select box to select the items and a search box to search the                                   

items and a button within it.  

Select box:  

● The <select> element is used to create a drop-down list. ● The <option> tags inside the <select> element define the available options in the                         

list. ● The <select> element is a form control and can be used in a form to collect user                                 

input. 

➔ In the tiles.component.html file, type the following code as 

19

<form class="form-inline"> <div class="form-group">

<label for = "selectbox" >Filter By:</label> <select [(ngModel)] = "selectedFilter" id="selection" name="filterBox">

<option *ngFor = "let filter of filterOptions">{{filter}}</option> </select></div> </form>

➔ In the tiles.component.ts file, create an array and type the filtered values. 

filterOptions : Array<string> = ['name','price', 'model']

➔ In the browser the select box is displayed with filtered options within a panel area. 

   

Input box:  

● <input> elements are used within a <form> element to declare input controls that                         allow users to input data. 

● An input field can vary in many ways, depending on the type attribute. ● Use the <label> element to define labels for <input> elements. ● You can give the input elements within the forms element. 

 ● In the tiles.component.html file, give the code like, 

 

<div class="form-group"> <label for="filtertext">Filter Text</label>

20

<input type = "text" [(ngModel)] = "filtertext" name="filtertext" id="filtertext" class="form-control">

</div>  

 

● In the browser, the input box will appear where you can type the filtered text.  

   

Button:  

● You can add button to submit the filtered text to apply search on items. ● In the tiles.component.html, create a button inside the forms tag. 

</div> <div class="form-group"> <button class="btn btn-success" (click) = "filter()">Apply</button>

● In the browser window you can see the output as follows.  

 

● For filtering the items in the array, use an temparory array to filter the values.   

21

● For that, type the below code in the tiles.component.ts file. 

export class TilesComponent implements OnInit{ imagePath:string = "/assets/images/"; filterOptions : Array<string> = ['name','price', 'model'] selectedFilter:string="name"; filterText:string = " "; filteredTiles : ITile[]; tiles:Array<ITile> =[{ // type the attibutes and values { ];

 

● Then write the code to give the function to the button. so that, when the button is                                 clicked the filter will happen. 

filter(){ this.filteredTiles = this.getFilteredTiles(this.selectedFilter,this.filterText); } getFilteredTiles(filterOption,filterText){ var tempTiles : ITile[] = this.tiles.filter(function(tile){ var isMatch:boolean = false; switch (filterOption) { case "name": if (tile.name.toLocaleUpperCase().indexOf(filterText.toLocaleUpperCase()) >= 0) { isMatch = true; return isMatch; } break; case "price": if (tile.price > Number(filterText)) { isMatch = true; return isMatch; } default: if (tile.name.toLocaleUpperCase().indexOf(filterText.toLocaleUpperCase()) >= 0) { isMatch = true; return isMatch; } break;

22

} return isMatch; }); return tempTiles; }}

● In the browser, the output will be displayed like this,  

 Three ways to communicate between angular components: 

1. Passing the reference of one component to another 

2. Communication through parent component 

3. Communication through Service 

 Nested Components:  ❖ A Component in Angular can have child components. Also, those child components can                         

have their own further child components. Angular seamlessly supports nested                   components. 

❖ An application in Angular is a set of custom components glued together in HTML via                             inputs and outputs. 

23

❖ So far we’ve only built applications with a single component, our goal now is to start                               building applications that are composed of multiple components working together. 

❖ Breaking up an application into multiple logical components makes it easier to:  

➢ Architect an application as it grows in complexity. ➢ Re-use common components in multiple places. 

 ❖ Similarly, Most Angular apps will have a root component called AppRoot or                       

AppComponent, this typically just acts as a container to hold other components.  

Creating tile component :  

● Ideally in our application tilecomponent should be responsible for displaying the tile                       and tiles componet should be limited to only loop and call the tile component. 

● If we use one component inside another component we call that as nested                         component. 

● Create the tile component by using the following command in the node promt,  

Command: ng genereate component tile  

● In the explorer you can see the tiles component is created, 

  

➔ To nest the component, do the following steps. ➔ Move the data from the tiles.component.html file to the tile.component.html file. ➔ For using the child component( tile.component.html) in your parent componet(                   

tiles.component.html), ◆ Type the child component’s selector (<app-tile> </app-tile>). Inside the body                   

element of the parent component. 

24

➔ But, when you try to run our applcation it will show error like property undefined.  

 

➔ So we need to define the tile in the tile.component.ts file, and declare it as ITile                               interface. 

export class TileComponent implements OnInit { tile:ITile; constructor() { } ngOnInit() { } }

 ➔ ITile interface which consist of all the attributes we required. ➔ Now we need to intialize the variable. Because, it is still a null value. 

 Component Communication:  

● Components need to communicate each other by input binding using via properties. ● Let's extract the tile component from the tiles component. ● Tiles component should loop through tiles and call tile component render the tile 

data. ● Tile component take the tile data from the tiles component and render. ● After all we need to bind the data through property binding. 

property binding in component communication: 

● The parent component can pass data to the child component through properties.  ● By using the @Input decorator for decorating a class property. ● In tile component class we decorate the tile with @Input() ● @Input() tile:ITile; ● In tiles component template we pass the data as property binding. ● <app-tile [tile]='tile'></app-tile>. 

 ❏ @input is used to decorate the component from the another source. 

25

❏ In the tile.component.ts file give the @input decorator.

export class TileComponent implements OnInit { @Input()tile:ITile; imagePath:string = "/assets/images/"; constructor() { } ngOnInit() { } }

❏ In the tiles.component.html file set the property binding for the selectorcomponent.

<app-tile [tile] = 'tile'> </app-tile>

 

❏ [tile] is not a standard property, it is a custom property binding. ❏ And also ‘tile’ is not a attribute here, it is an object which is applied to the @input 

decorator. ❏ Now, you run the program and the output will be display like follows, 

 

 Component types: 

26

 ● Components to be used in either ways as, 

1. Attribute 2. Element  

● By default it is element and we need to use the component as element in our case 

<app-tile> <app-tile> 

● Here, the element is nothing but the selector and the selector may be anythinng. ● We can specify our component to be used as attribute directive. For this when we 

define the selector in the component decoration we need to put that inside square brackets. 

● A component can be used as an attribute to any other element or component can be used itself as an element. 

● For that, you need to decorate the selector in the component as attribute in the tile.component.ts file.

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

● In the tiles.component.html file, create the attribute inside the <tr> element with the 

name of app-tile instead of creating it in outside. 

<tr *ngFor ="let tile of filteredTiles" app-tile [tile] = 'tile'>

● Here, the tile will look for the app-tile attribute as it doesn’t look for the <tr> element 

27

● The output will be displayed as the same, when you use component as element as well as component as attribute. 

SERVICES:  

● A service in angular is an object that provide some sort of service that can be reused with an angular application. 

● It is irrespective of whether a service has an injected dependency or not. ● It always decorate the angular service class with @injectable() decorator for 

consistency and future proof. ● If a service is registered in a component level, then that service is available only to 

the component and to it’s children. ● If a service is registerd in a module level, than that service is available to all the 

components in the application.  

Why angular services?  

❖ You need to retrieve data from or send data to your server. ❖ You need to encapsulate application logic that is not specific to any one component, 

or logic that can be reused across components. ❖ You need to share data across components, especially across components that may 

or may not know about each other. 

Creating service:  

● Go to the angular cli, and type the command as follows, 

ng generate service tile 

● In the node prompt you can see the .ts and .spec.ts file will be created, 

 

28

● Go to the tile.service.ts file and see there is a decorator called @injectable. 

@injectable : 

● @Injectable() lets Angular know that a class can be used with the dependency injector.  

● @Injectable()is not strictly required if the class has other Angular decorators on it or does not have any dependencies.  

● What is important is that any class that is going to be injected with Angular is decorated. 

● However, best practice is to decorate injectables with @Injectable(), as it makes more sense to the reader. 

 ➔ I dont want my components to hold data within it. So move all you data to the service.ts 

file. ➔ In the tiles.component.ts file it will complain like property ITile is is doesn’t exist. so , type 

the following code.  

tiles:Array<ITile>; 

 

Custom services: 

❖ Custom service is the one which we can write to get our custom tasks. ❖ To create our own service first we need to create angular module then connect our 

custom service to angular module   

getTiledata(): 

● In our tilescart application, we are creating our own service with the name tileservice to do all our bussiness logic. 

● Actually, we need to get the data from the external services like http. But, here we are using our own services. Angular will allow us to create our own services. 

● getTiledata() it is a method, that we hard coded it for getting the tiles data.   ➢ In the tiles.component.ts file, after the class file, ➢ Within the constructor method. create a tileservice object as follows,  

constructor() { this.filteredTiles = this.tiles; this.tileService = new TileService(); } 

29

➢ Within the ngOnIt method. Type the code as follows, 

ngOnInit(){ this.tiles = this.tileService.getTileData(); this.filteredTiles = this.tiles; } 

 ● ngOnInit lifecycle hook is called when the component gets initialized. It is the right hook 

to get the data from the external system and populate the data.  

● In the tile.service.ts file the place in which we need to move our data is next to the @injectable() decorator. 

@Injectable({ providedIn: 'root' }) export class TileService { tiles:Array<ITile> =[{ // your data inside the array }]

❖ At last run the application and the output will look like the following, 

  

 

 

30

DEPENDENCY INJECTION: 

● Dependency Injection (DI) is a way to create objects that depend upon other objects. ● A Dependency Injection system supplies the dependent objects (called the 

dependencies) when it creates an instance of an object. ● Dependency injection is the idea that any class or function should ask for its 

dependencies, rather than instantiating it themselves.  ● Something else (usually called an injector) would be responsible for figuring out what 

is needed and how to instantiate it. ● In our case study => in the tiles component we have specified tile service as 

dependency and angular has automatically created the instance of the service and injected to the component. 

● It follows the singleton pattern even if we multiple components make use of the same service there will be only one instance of the service 

Importance of using dependency injection: 

1. loosely coupled code 2. more flexible code 3. easier to test 

 Creating a dependency:   

export class tilescart(){ dataservice : Dataservice; constructor(){ this.dataService = new DataService(); }}

 ● The tilescart component is tightly coupled with the type of dataservice we created here.  

 Injecting a dependency:  

export class tilescart {  constructor (private dataService : DataService){ } } 

 ● Here we are passing instance of the classes inside the parameters declared on the                           

constructor. ● The DataService instance in which the service is depends on. 

 

31

COMPONENT LIFE CYCLE: ● Every Angular component has a lifecycle. Actually, every Angular component and Angular                       

directive have a lifecycle and the following information can be applied to both.  ● The lifecycle is managed internally by Angular. 

  Angular , 

➢ Creats it, ➢ Renders it, ➢ Render it’s children, ➢ Checks it when data bound properties change, ➢ Destroys it before removing from the DOM. 

 

LIFE CYCLE HOOKS:  

★ Angular offers lifecycle hooks that provide visibility into these key life moments and                         the ability to act when they occur. 

★ A directive has the same set of lifecycle hooks. ★ We need to learn only 3 steps to use lifecycle hooks, they are: 

1. Import Hook interfaces from ‘@angular/core’ library. 2. Declare that component/directive implements lifecycle hook interface. 3. Create the hook method and define the functionality of that method. 

 8 Lifecycle Hooks: 

● ngOnChanges() 

○ Used in pretty much any component that has an input. ○ Called whenever an input value changes ○ Is called the first time before ngOnInit 

 ● ngOnInit() 

○ Used to initialize data in a component. ○ Called after input values are set when a component is initialized. ○ Added to every component by default by the Angular CLI. ○ Called only once 

 ● ngDoCheck() 

○ Called during all change detection runs ○ A run through the view by Angular to update/detect changes 

32

  

● ngAfterContentInit() 

○ Called only once after first ngDoCheck() ○ Called after the first run through of initializing content 

 ● ngAfterContentChecked() 

○ Called after every ngDoCheck() ○ Waits till after ngAfterContentInit() on first run through 

 ● ngAfterViewInit() 

○ Called after Angular initializes component and child component content. ○ Called only once after view is initialized 

 ● ngAfterViewChecked() 

○ Called after all the content is initialized and checked. (Component and child                       components). 

○ First call is after ngAfterViewInit() ○ Called after every ngAfterContentChecked() call is completed 

 ● ngOnDestroy() 

○ Used to clean up any necessary code when a component is removed from the                           DOM. 

○ Fairly often used to unsubscribe from things like services. ○ Called only once just before component is removed from the DOM. 

 

Angular built-in services: 

● Angular has many built in services which help in performing day to day development                           activities and most popular are http service and log service. 

● Http service is used for ajax calls and log services is for debugging our application in                               the console. 

● In that, Http service is used to interact with the back end to get the data and post the                                     data.  

● We have four operations which we do on http services  

○ Get - get the data from the back end service ○ Post - post the data  ○ Update ○ delete 

 

33

HTTP service:  

● Most front-end applications communicate with backend services over the HTTP                   protocol. 

● Angular provides @angular/common/http library for communicating with a remote                 server over HTTP. 

● We will call Http Web Services (REST Services) using HttpClient. ● To make HttpClient available everywhere in the app, 

 ○ Open the root AppModule, ○ Import the HttpClientModule symbol from @angular/common/http. ○ Add it to the @NgModule.imports array. 

 ● Now we require remote data server which provides HTTP Web Service, which we can                           

call using Angular Front End. ● You can create Web Service in any language like Java, PHP, .Net or NodeJS. We can                               

consume this web service using HttpClient in an angular app.  

Tiles service to get data from web api:  

● In our tiles cart app we have hard coded the data in the tile service. Instead we                                 should get the data from the back end. 

● Lets refactor our tiles service to get the data from the back end service instead hard                               coded tile data.  

 Using http service:  

● Http services is not available in the core angular. It is available in the                           HttpClientModule . we need to import the HttpClientModule and specify it as                       dependency in the app.module.ts.  

app.module.ts: import {HttpClientModule} from '@angular/common/http'; imports: [ BrowserModule,FormsModule,HttpClientModule ]

      

34

Using http service in the tile service: 

tile.service.ts: import {HttpClient} from '@angular/common/http'; import { Observable } from 'rxjs'; constructor(private _httpClient : HttpClient) { }

 WEB API:  

➔ A Web API is an application programming interface for either a web server or a web                               browser.  

➔ It is a web development concept, usually limited to a web application's client-side                         (including any web frameworks being used), and thus usually does not include web                         server or browser implementation.  

Web API Features:  

● It supports convention-based CRUD Actions since it works with HTTP verbs                     GET,POST,PUT and DELETE. 

● Responses have an Accept header and HTTP status code. ● Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML                   

or whatever format you want to add as a MediaTypeFormatter. ● It may accepts and generates the content which may not be object oriented                         

like images, PDF files etc. ● It can be hosted with in the applicaion or on IIS(InternerInformationServices). ● It also supports the MVC features such as routing, controllers, action results,                       

filter, model binders, IOC container or dependency injection that makes it                     more simple and robust.  

Web API in our application:  

❏ Typically all our app data like tiles,users,orders,customer all details are stored in the                         data base. 

❏ In the UI of the app if we want to use these data we need to expose them as API                                       which can be called from the browser. 

❏ Typically a web api is an API which is written on the middleware/back ground and can                               be called from the browser. 

❏ I mean if we need to call the web api we need to have the URL which is pointer to the                                         web api. 

❏ The rest api and web api are both are same.      

35

 Mocakable.io:  

❖ We can write web api using the real options like web api using C# or Java or we can have the mock api which mimic the actual data call but returns the JSON as output. 

❖ Mockable io is an Mock Web API which we can mimic the web api call which returns the mock data.  

Mock service: 

● Let’s assume, you want to get a JSON or XML response from a back end service, but within the given time, you cannot create a back end service that will trigger such a response. 

● Therefore, in such scenarios, you can create a mock service which will trigger any type of response you want to test your web service. 

 ❖ Go to the browser and type as mockable.io and first register on that, 

 

  

❖ Click on the manage in the screen, to manage the mocks in the domain.  

  

❖ After that click on the add rest mock option that will appear on the screen.  

 

36

❖ There is an url shown in the screen, inside the text box type as tiles to call the tiles,  

  

❖ Move your data to the output json file which is on the same screen below,  

  

❖ This is a JavaScript object. So, we neeed to convert it into JSON object. ❖ For that, go to the node.js file and type as, 

 

JSON.stringify ( data ) 

 ❖ You can see the output like below in the node.js file, 

 

     

37

❖ Now you can copy and paste the output file(JSON data) in the place of the JavaScript object data. And click on the save button. 

 

  

❖ Also click on the stopped button to start the mock.  

  ❖ Here is the link to get the tiles at the top of the window, 

 

  

 Postman tool:  

● Postman is a powerful tool for performing integration testing with your API.  ● It allows for repeatable, reliable tests that can be automated and used in a variety of 

environments and includes useful tools for persisting data and simulating how a user might actually be interacting with the system. 

● Here in our application, we are using the tool for verifying the output of the web api.  Work of a postman:  

➢ Postman is a Google Chrome app for interacting with HTTP APIs.  ➢ It presents you with a friendly GUI for constructing requests and reading responses. ➢ The people behind Postman also offer an add-on package called Jetpacks, which 

includes some automation tools and, most crucially, a Javascript testing library. 

38

➢ This post will walk you through an example that uses those testing features.  ➢ This makes it extremely valuable for functional testers or for developers who love to 

test outside-in.  6 reasons to use postman:  

1. Easily create test suites. 2. Store information for running tests in different environments. 3. Store data for use in other tests. 4. Integrates with build systems, such as Jenkins using the Newman command line tool. 5. Easily move tests and environments to code repositories. 6. Easily move tests and environments to code repositories. 

 ● Go to the postman tool and run it whenever it gets entered into the tool it will show 

some options, in that select the option as Request.  

  

● Click cancel to the request. ● Now you can see the window in which select the GET method and paste the url there in 

the text box. And click on that send button.  

        

● Now you can see the data on the screen in the form of JSON, after sending the request. 

39

 

  SYNC & ASYNC: Synchronous communication:  

● It is a kind of communication where we call the destiny and wait till it gets connected and get the required response until we get the response we require. 

● Like phone communication where receipent picks the call and answers all the queries and then we disconnect. 

● In all the conversations we are connected with the server.  

Asynchronous communication:  

● In Asynchronous communication we connect to the destination and ask for information but we dont hang on to get the response. 

● Inturn we leave a function to call back with answer to query. ● It is like sms communication we connect to the client post query but we will not hang 

on till he gives the response. ● We will give his free time to respond with data. ● In similar passion browser ask for the required data in async mode and leave a 

function in our case subscription to call back with the required data.  

❖ In the tile.service.ts file type the code as follows,  

private tileURL:string = 'http://demo5911200.mockable.io/tiles'; // url for the mockable io getTileData():Observable<ITile[]>{ return this._httpClient.get<ITile[]>(this.tileURL); }

❖ In the tile.component.ts file, type the following code. 

40

 

ngOnInit(){ this.tileService.getTileData().subscribe((tiles)=>{ this.tiles = tiles; this.filteredTiles = this.tiles; }); 

 NOTE : ALWAYS USE THE ARROW FUNCTIONS AS THE CALL BACK FUNCTIONS WHEN MAKING CALLS TO HTTP SERVICES.  Observable:  

● Observables provide support for passing messages between publishers and subscribers in your application. 

● Observables offer significant benefits over other techniques for event handling, asynchronous programming, and handling multiple values. 

● Observables are declarative, you can define a function for publishing values, but it is not executed until a consumer subscribes to it.  

● The subscribed consumer then receives notifications until the function completes.  Usage and Terms:  

● As a publisher, you create an Observable instance that defines a subscriber function.  ● This is the function that is executed when a consumer calls the subscribe() method. ● The subscriber function defines how to obtain or generate values or messages to be 

published. ● To execute the observable you have created and begin receiving notifications, you 

call its subscribe() method, passing an observer.  

➔ In a real-world example, we can say that the Internet service offered by mobile devices is an observable. It is available only to the people who have subscribed to it. We continuously receive this service from the service provider only as long as this service is on and we are subscribed to it.  

 ❖ Finally the output will be displayed as follows, this time the data is get from the external 

resouce. 

41

 

   Deep Nesting: 

 ➔ Angular development recommends to create as many components as possible which 

can be reused across. ➔ Lets create star component out from the tile component . ➔ We use star component to display the rating as stars instead the number. 

 Let's create star component ,  

ng generate component star 

 ● You can see the star component created in the explorer window. 

 

 

 

 

 

Font-awesome font-library,  

◆ We will be using the new library font-awesome to display stars in the UI.  

42

◆ We need to below steps for using the font-awesome .  

● First install the font awesome from the library.  

npm install font-awesome angular-font-awesome 

 ● Now copy and paste the link file into the angular.json file, 

 

../node_modules/font-awesome/css/font-awesome.css" (refer it in the angular.json) 

 ◆ <span class="fa fa-star" > </span> to use it the star component. ◆ In the star.component.html file, type the code as follows, 

 

<div style="width:65px"> <span class="fa fa-star checked" ></span> <span class="fa fa-star checked" ></span> <span class="fa fa-star checked" ></span> <span class="fa fa-star checked" ></span> <span class="fa fa-star checked" ></span> </div> 

 ● Go to the tile.component.html, and type the selector for the star.component file. 

 

<td><app-star></app-star></td> 

 ❖ We need register in the app.module.ts file. so, go and import the star component first. 

import { StarComponent } from './star/star.component'; @NgModule({ StarComponent, })

       

● Now run the program and you can see the output as ,  

43

  ● But we need to show the stars according to the rating given. ● We need to pass the data into the rating, for that we use property binding here. 

  

<td><app-star [rating]='tile.rating'></app-star></td> 

 ● The star component taking the width as 65px, so we need to control the width to fit if we                                     

give two stars, three stars and so on. ● For that we create a variable called ratingwidth. With which we can control the                           

components width. ● In the star.component.html file, create one more div element before the current div                         

element,  

<div [title]="rating" [style.width.px]="ratingWidth" style="overflow: hidden;"> 

 ● In the star.component.ts file, declare a variable called ratingwidth as follows,  

@Input() rating; ratingwidth:number = 65; 

 OnChanges:  

➔ If we want to get handle over i.e want to execute any code when the input variable in                                   the component change we are going implement    

 ◆ In our tilecart app we want to update the ratingWidth whenever rating field value is                             

changed.  

44

◆ Hence we implemented the OnChanges and updated the ratingWidth on                   ngOnChanges method in the star.component.ts file. 

 

@Input() rating; ratingWidth:number=65; ngOnInit() { } ngOnChanges(){ this.ratingWidth = this.rating * 65/5; } 

 ➔ Now run the program, and you can see the output like this, 

  ROUTING:  

★ Angular provides an easy way to create and work with components , In a single page                               application(SPA). 

★ It is essential to work with multiple views/screens, navigate and communicate                     between them.  

★ Angular provides router service to manage this in a very easy way. ★ In Angular routing means moving from one component to another component. 

 ○ once the user loads the app we load loginComponent. ○ once the user enter credentials and login we will redirect user to the tile                           

listing. ○ once the user select the tile we will move to the tileDetailComponent. 

    

45

Defining routing:  ● In an application we may have “n” number of routes are there. ● Routing is defined in the routing module if we want to use the routing module then we                                 

need to import the routing module in the app module. 

import {RouterModule} from '@angular/router'; imports: [ BrowserModule,FormsModule,HttpClientModule,RouterModule ]

 ● Routing is nothing but the routes configuration. 

Routes is an interface which contains below properties.  

interface routes{ path:string; component:Component } 

 ● Mean we need to define the routes that are applicable in the application 

 Our routes array:  ● Import routes from the @angular/router and define the routes. ● Here route is the array of component of key value pair. ● We are just defining the array inside the app.module.ts file. 

import {RouterModule,Routes} from '@angular/router'; const appRoutes : Routes = [{ path:"login", component : LoginComponent}, {path:"tiles", component : TilesComponent}, {path:"",pathMatch: 'prefix', redirectTo:"login"}, {path:"**", redirectTo:"login"} ];

● Import the appRoute array as follows,

imports: [ BrowserModule,FormsModule,HttpClientModule,RouterModule.forRoot(appRoutes) ],

46

Router-outlet:  

● Router-outlet is the placeholder directive where the all components get loaded on the                         routing. 

 ○ If we load the login component then login component is loaded inside this directive. ○ Once me move from login component to the tiles component then the dom and html                             

of login component are unloaded from the router-outlet and tiles component html                       and dom is loaded. 

○ Mean at given point the active component is loaded into the routing component.  

● Now go to the app.component.html and type the following code,  

<div> <nav class='navbar navbar-default'> <div class='container-fluid'> <a class='navbar-brand'>{{pageTitle}}</a> <ul class='nav navbar-nav'> <li><a [routerLink]="['/tiles']">Tile List</a></li> </ul> <ul class='nav navbar-nav navbar-right'> <li><a [routerLink]="['/login']">Login</a></li> </ul> </div> </nav> <div class='container'> <router-outlet></router-outlet> </div> </div> 

 ● The output will display linke this, 

 

  

47

● Once the users logins in successfully we need to redirect to the tiles. ● If we need routing through api we need to use the router service available in                             

routermodule. ● Import the router and specify as dependency and redirect on login. ● import {Router} from '@angular/router'; (in login.component.ts file). ● As per the dependency injection we need to specify the routeservice inside the                         

constructor.  

constructor(private _routerService:Router) { }

  

● After that, we need to redirect to the another component. so ,follow the code below,  

this._routerService.navigate(['/tiles']) 

 ● Now, run the code and see the output. Check the url above it changes into tiles, 

 

  

WELCOME COMPONENT:

★ Just displays welcome page ★ A New component ★ ng generate component welcome ★ And put the welcome page data into the html 

       

48

● After creating the component, type the html code like follows1 

<div class="panel panel-primary"> <div class="panel-heading"> {{pageTitle}} </div> <div class="panel-body" > <div class="row" > <img src="./assets/images/logo.jpg" class="img-responsive center-block" style="max-height:300px;padding-bottom:50px"/> </div> <div class="row" style="padding:10px" > <form> <address> <strong>Mobile Kar Inc.</strong><br> Rajaji Nagar<br> Bangalore - 560782<br> <abbr title="Phone"> P: </abbr> 080 4635373 </address> <address> <strong>mobile kart</strong><br> <a href="mailto:#">[email protected]</a> </address> </form> </div> </div> </div>

. ● Update app component to have link for the welcome, 

<ul class='nav navbar-nav'> <li><a [routerLink]="['/welcome']">welcome</a></li> <li><a [routerLink]="['/tiles']">Tile List</a></li> </ul> <ul class='nav navbar-nav navbar-right'> <li><a [routerLink]="['/login']">Login</a></li> </ul>

 ● Update routing have welcome component route 

const appRoutes : Routes = [

{path:"login", component : LoginComponent},

{path:"tiles", component : TilesComponent},

49

{path:'welcome',component:WelcomeComponent},

{path:"",pathMatch: 'prefix', redirectTo:"login"},

{path:"**", redirectTo:"login"}

];

 ● Finally the output will display like as follows, 

 

   

Route Parameter:  ● Sometimes we need part of the path in one or more of our routes (the URLs) to be a                                     

variable, a common example of this is an ID. ● If we are using multiple routes in our componet, we need to code like the below, 

 ● const routes: Routes = [ 

{ path: 'tile/1', component: tile1Component },  { path: 'tile/2', component: tile2Component },  { path: 'tile/3', component: tile3Component },  { path: 'tile/4', component: tile4Component }, ]; 

 ● Instead a better solution is to have one route with one component called tileComponent                           

and pass to the tileComponent the number part of the URL.  

50

  ● That’s called a parameterised route and we would implement it like so: 

 

const routes: Routes = [ { path: 'tile/:id', component: tileComponent } ];

 ● The path has a variable called id, we know it’s a variable since it begins with a colon : 

A path can have any number of variables as long as they all start with : and have                                   different names. 

 

const routes: Routes = [ { path: 'tiel/:id', component: tileComponent }, { path: 'tile/moo', component: MooComponent }, ]; 

 ● Non-parameterised routes take precedence over parameterised routes. ● Typically in any app we need to route along with some parameters passed to the other                               

component. ● The receiving component fetch those parameters and query the web api to get only                             

those required data   

TilesCart:  ● We create tileDetailComponent to see more details of the selected Tile. we enable                         

routing here and pass the selected tile id to the tileDetailComponent .  Activated Route:  ❖ ActivatedRoute is the service which is available in the router module which helps in                           

accessing the parameters supplied along with the route. ❖ We need to specify this service as dependency on component/service where we we need                           

to access the parameter. ❖ First create a tileDetail component. ❖ ng generate component tileDetail  ❖ You can see the tiledetail component created in the explorer window. 

 

51

  Linking Tiles Component:  ● Enable linking on the tilesComponent by passing the tile id.  ● tileData does not contain the tileid update the web api to include the tileid. 

 

<td><a [routerLink]="['/tiles',tile.Id]">{{tile.name}}</a></td>

➔ Routing to include the tileDetailComponent,  

const appRoutes : Routes = [ {path:"login", component : LoginComponent}, {path:"tiles", component : TilesComponent}, {path:"tiles/:Id",component:TileDetailComponent}, {path:'welcome',component:WelcomeComponent}, {path:"",pathMatch: 'prefix', redirectTo:"login"}, {path:"**", redirectTo:"login"} ]; 

 ➔ The route will be made to the tileDetail component and the output will display like, 

 

  

tileDetailComponent,  

❖ Template : This template should contain the individual tileDetails and an option with actions to                         peform like add to wishlist, cart or buy. 

❖ In this component we need to fetch the params that are supplied as part of the route                                 in our case it is Id of the component for which details needs to be displayed.  

52

Import and specify the the ActivateRoute as dependency import {ActivatedRoute} from '@angular/router'; constructor(private activateRoute:ActivatedRoute) { }

     

❖ In the tileDetail.component.html type the following code,  

<div class='panel panel-primary'> <div class='panel-heading'> Details of the mobile {{tile.name}} </div> <div class='panel-body'> <div class='row'> <div class='col-md-3'> <img [src]='imageUrl+tile.image' style="height:75px;width:75px;" /> </div> <div class="col-md-3"> <div class="row"> <div class='col-md-2'>Id</div> <div class='col-md-4'> {{tile.Id}} </div> </div> <div class='row'> <div class='col-md-2'>name</div> <div class='col-md-4'> {{tile.name}} </div> </div> <div class='row'> <div class='col-md-2'>model</div> <div class='col-md-4'> {{tile.model}} </div> </div> </div> <div class="col-md-3"> <div > <button (click)="navigateBack()" style="width:100px" class="btn-primary">Go Back</button> </div> <div > <button style="width:100px" class="btn-primary">Wish List</button> </div> <div > <button style="width:100px" class="btn-primary">Buy</button> </div> </div> </div> </div> </div>

  

53

        

❖ The output of the code will display like the below,  

  ngOnInit of tileDetailComponent:  

★ Fetch the Id of the selected Tile and log to the console.  

constructor(private activateRoute:ActivatedRoute) { } ngOnInit() { let id = +this. _activatedRoute.snapshot.paramMap.get('id'); console.log(id); }

 Mockable io update for the tile id: 

tile:ITile= { "name": "nitco", "model": "nit-01", "price": 200, "rating": 2, "image": "tile1.jpg", "status": 1, "Id": 1 }, { "name": "johnson", "model": "nit-02", "price": 100, "rating": 4,

54

"image": "tile2.jpg", "status": 0, "Id": 2 }

     

● After hard coding the tiles the tileDetail component will display like this,  

  

● In order to get the activated tile data follow the steps,  

import { ActivatedRoute, Router } from '@angular/router'; constructor(private _activatedRoute,ActivatedRouter) { }

 ● After that create a variable called Id, it is nothing but whatever we are getting as output                                 

from activated route. ● In the ngOnIt, 

  ngOnInIt(){ let id = +this.activateRoute.snapshot.paramMap.get('id'); console.log(id); } 

 ● Here paramap is a object with key value pair. ● Activated route takes the snapshot of every parameter.whenever you wnat you can use                         

the api(snapshot). ● + for converting into type number, otherwise it will try to get it as a string  ❖ Create more than one rest mock, in which it contains individual data of tiles. 

 

55

   ❖ Now go to the postman and give the link url and click on send. 

 

  ❖ The respective json file of that link will be displayed like below,  

  

tileService to get the Data for Require tileId: 

getTile(id:number): Observable<ITile> { return this._httpClient.get<ITile>(this.tileAPIURL+`\\${id}`) }

 ● In the tile-detail.ts file type the code like this, 

 ngOnInit() { let Id = + this. _activateRoute.snapshot.paramMap.get('Id'); console.log(`parameter received is ${this.Id}`); this._tileService.getTile(this.Id).subscribe( (tile)=>{ this.tile = tile; } ) 

 ● Run the program and you can get the required output, 

 

56

    tileDetailComponent with tileService:  

imageUrl:string = "assets/images/"; tile:ITile; ; errorMessage: any; constructor(private activateRoute:ActivatedRoute,private _tileService:TileService) { } ngOnInit() { let id = +this.activateRoute.snapshot.paramMap.get('id'); this._tileService.getTile(id) .subscribe(tile => { this.tile = tile; }, error => this.errorMessage = <any>error); this.tile = this.tile; } 

 Navigate back to tiles:  

● In the tiledetail.ts file set the router for the service as below,  

constructor(private _activateRoute:ActivatedRoute, private _tileService:TileService,private __router:Router) { } //here router is a service 

 ● Route the component to the tiles component by using the function inside the                         

tile-detailcomponent.  

navigateBack(){ this.__router.navigate(['/tiles']); } 

 ● Finally when u click on the goback button it will navigate to the tiles component.  

57

  

   

FORMS:  

● Forms are the mainstay of business applications. You use forms to log in, submit a                             help request, place an order, book a flight, schedule a meeting, and perform countless                           other data-entry tasks. 

● In developing a form, it's important to create a data-entry experience that guides the                           user efficiently and effectively through the workflow. 

● Developing forms requires design skills (which are out of scope for this page), as well                             as framework support for two-way data binding, change tracking, validation, and error                       handling, which you'll learn about on this page.  

Building angular forms:  

❖ Build an Angular form with a component and template. ❖ Use ngModel to create two-way data bindings for reading and writing input-control                       

values. ❖ Track state changes and the validity of form controls. ❖ Display validation errors to users and enable/disable form controls. ❖ Share information across HTML elements using template reference variables. 

 There are two types of angular forms:  

1. Template-driven forms, 2. Reactive forms.  

● Use template-driven forms when developing static forms. Static means the structure                     and logic of a form is fix. 

● E.g. the number of form fields does not vary, form validation rules are the same for                                 different user roles, etc.  

● Examples of template forms:   

1. login forms,  2. reset password forms, 

58

3. forms to enter and edit address data, 4. order data and similar fix data structures.  

● In the template-driven approach the form structure and logic is mainly implemented                       in HTML. Based on this a representation of the form in TypeScript is generated                           automatically.  

Template-driven forms:  

➢ One-way and two-way data-binding. Forms to enter new data and to edit existing data                           (from a backend service) can be developed. 

➢ Creation of nested form fields, e.g. a form containing a user model consisting of user                             name, email address and postal address — consisting of street, city, zip code. 

➢ Field-spanning validation, e.g. validate entire user model instead of checking each                     field individually. 

➢ Synchronous and asynchronous validation, e.g. check via remote server whether                   email address exists. 

➢ Checking form state, e.g. warn when leaving the form with unsaved changes  

Reactive forms:  

➢ Reactive forms provide a model-driven approach to handling form inputs whose                     values change over time. 

➢ Reactive Forms are opposite to template-driven forms. Instead of defining the form                       in your template, the structure of the form is defined in code. 

 Examples:  

1. dynamic survey forms,  2. forms to add/delete 0..n tags or phone numbers, 3. forms providing different validation for different user roles, etc. 

 Login Component:  

● In our login component we are not doing much validations on the UI. ● Lets we update our login component to do validations like, 

○ Required, ○ Pattern, ○ Etc 

 HTML5 attributes:  

● Attributes provide additional information about HTML elements. ● HTML5 attributes are case insensitive and may be written in all uppercase or mixed                           

case, although the most common convention is to stick with lowercase. ● Html5 consists of many custom attributes in HTML5, Lets update the login                       

component to have these attributes to do the validation. 

59

Required:  

● A "Required Field" is a field that must be filled in with value before submission of a                                 form.  

● Required field sometimes known as Mandatory field or Compulsory field. ● As of writing, only Opera and Firefox support "Required" attribute of input textbox. ● Any field with the required attribute must also have a name attribute.  ● Fields without names are not a part of submission, so are ignored in validation. 

 ❖ In the previous login component add the required attribute after the username to make                           

it as required. 

<input type="text" name="Username" id="Username" [(ngModel)] = "Username" required/>

User name required and error message:  

● Make user name fields on the UI as required. ● <input type="text" name="Username" id="Username" [(ngModel)] = "Username" required/>

● If the user is not entered lets add another div next to the use name to display error                                   message. 

<div class = “alert alert-danger”> User name is required </div>

● The user alert will display like below,  

  

● I want to show the alert only after the focus or type nothing inside the text box. But,                                   not by default. 

 Hidden Directive:  [hidden] : angular has a built in directive called hidden which accepts an expression. 

● If the expression is true it will hide the content of specified element. ● Elseif it will display the conent 

 In our login component we want to show the user name error message if the user name                                 fiels is valid and it is pristine. 

60

● Here we are just hard coding the div to hide the alert message by using,  

<div [hidden] = "true" class= 'alert alert-danger'> User name is required </div> 

 

  

Pristine:  

● We can call it as pristine or we can call it as dirty. ● In angular pristine mean whether given control is modified by the user or not. ● Mean does he focus and tried entering the value. 

 

<div [hidden] = "uname.valid || uname.pristine" class= 'alert alert-danger'> User name is required </div> 

 Template reference variable:  

➢ In angular we should give alias for the every control which we call it as template                               reference variable, to wich angular updates whether it is pristine or valid. 

➢ A template reference variable is an accessor to the input box angular control within                           the template. 

➢ We create a variable and assign it value ngModel. ➢ ngModel actually holds the value of the control. ➢ Template reference variable contains the reference to the control value so that it can                           

check whether it has value, is that valid, etc  

<input type="text" name="Username" id="Username" [(ngModel)] = "Username" required #uname="ngModel"/> </div> <div [hidden] = "uname.valid || uname.pristine" class= 'alert alert-danger'> User name is required </div>

       

61

● So when u tap out of the text box it will show the alert,  

   

● Follow the same steps to create the alert for the password also,  

<input type="password" name="password" id="password" [(ngModel)] = "password" #upwd = "ngModel" required /> </div> <div [hidden] = "upwd.valid || upwd.pristine" class="alert alert-danger"> password is required </div> 

  

  Template reference variable for form:  

● Enable button only if the form is valid. For that follow the steps, ● For diabling the button, set the attribute as [disabled] = “true”. 

   

62

● The disabled button will look like as follows,  

  ● Now set the condition for the button, as it will enable only if the form is valid. ● If we want to create a template reference variable for a form you need to assign it as                                   

ngForm.  

<form name="login" #loginForm = "ngForm">

● Go to the button and give the code to check whether the form is valid or not.  

<div><button class ="btn btn-primary" (click) = "login()" [disabled]="!loginForm.valid"> Submit</button></div> 

 ● After when the form is checked to be valid, the button will display in that the user will 

click to submit the form. 

        

 

63

REGULAR EXPRESSION (regex or regexp):  

1) A regular expression is a special text string for describing a search pattern. You can                             think of regular expressions as wildcards on steroids. 

2) A sequence of characters that define a search pattern. Usually this pattern is then used                             by string searching algorithms for "find" or "find and replace" operations on strings, or                           for input validation. 

3) For instance, you could use the regular expression as,  \b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}\b   

to search for an email address. Any email address, to be exact. 4) A very similar regular expression can be used by a programmer to check if the user                               

entered a properly formatted email address, In just one line of code. 5) Regular expressions are used in search engines, search and replace dialogs of word                         

processors and text editors. 6) The regular expression is sometimes called as rational expression. 

 PATTERN MATCHING:  Lets update our login component user name to contain email as valid user name. Regular expression for the email pattern is /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/   Update our uname field to have the regular expression

<input type="text" name="userName" id="userName" class="form-control" pattern="^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$" [(ngModel)]="userName" required #uName="ngModel">

Add error message if the error is due to the invalid pattern

64

<div *ngIf="((!uName.valid) && uName.errors?.pattern )" class="alert alert-danger"> user name does not match with the pattern </div>

Now when we enter to user name which is not valid email it will through error message displayed Reactive form Component Introduction here #1 import the reactive form module import { ReactiveFormsModule } from '@angular/forms'; imports: [ BrowserModule,FormsModule,HttpClientModule,ReactiveFormsModule, RouterModule.forRoot(appRoutes) ] #2 create register component ng generate component register 

# update app.componet.html to link register component  

<ul class='nav navbar-nav navbar-right'> <li><a [routerLink]="['/register']">Register</a></li> </ul>

65

Reactive Forms:  ❖ Reactive forms provide a model-driven approach to handling form inputs whose values 

change over time. ❖ Reactive Forms are opposite to template-driven forms. Instead of defining the form in 

your template, the structure of the form is defined in code. ❖ Reactive forms take a different approach compared to that of the template-driven forms.

Here, we create and initialize the form control objects in our component class. ❖ They are intermediate objects that hold the state of the form. We will then bind them to the

form control elements in the template. ❖ The form control object listens to any change in the input control values, and they are

immediately reflected in the object's state. ❖ Since the component has direct access to the data model structure, all changes can be

synchronized between the data model, the form control object, and the input control values. ❖ In our application we are going to write our code in the class to,

■ Define all the controls along with the behavior like required,pattern,email etc in the component class.

■ This is use full when we are deriving the UI from the back end model. Importing ReactiveFormsModule: ● First we need to register the ReactiveFormsModule in our app.module.ts file, ● And also import the ReactiveFormsModule in the same file in the import section,

import { ReactiveFormsModule } from '@angular/forms';

imports: [ BrowserModule,FormsModule,HttpClientModule,ReactiveFormsModule, RouterModule.forRoot(appRoutes) ]

Register Component: ★ First create a register component on your application by using the command,

ng generate component register

★ After created the register component will be displayed in the explorer like below,

66

★ In the app.component.html file give the route link as register,

<ul class='nav navbar-nav navbar-right'> <li><a [routerLink]="['/register']">Register</a></li> </ul>

★ In the app.module.ts file update the route for the register component, 

 

{path:"register", component : RegisterComponent},

 ★ After applying these things, run your application and the register component will display 

like this,  

  

➔ Displaying our register component with a text box,  

<div class="form-group" > <label for="userName">User Name</label> <input type="text" class="form-control"> </div> 

 ➔ The output will display like follows, 

 

     

67

● Form control elements in template, model and data,  

❖ if we are building a form for updating the user profile, the data model is the user object retrieved from the server.  

❖ By convention, this is often stored inside the component's user property (this.user). ❖ The form control object or the form model will be bound to the template's actual 

form control elements.  ❖ Both these models should have similar structures, even if they are not identical. 

However, the input values shouldn't flow into the data model directly. ❖ The image describes how the user input from the template makes its way to the form 

model. 

Reactive forms in our tilescart application:

 

68