0% found this document useful (0 votes)
181 views100 pages

Angular 7 201 300

Angular services allow sharing data and functionality across components. A service is a class decorated with @Injectable that contains reusable business logic. Components can inject the service into their constructor to share data and methods. Data can be set in one component's service and accessed from another component's service. Services help avoid direct communication between sibling components.

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
181 views100 pages

Angular 7 201 300

Angular services allow sharing data and functionality across components. A service is a class decorated with @Injectable that contains reusable business logic. Components can inject the service into their constructor to share data and methods. Data can be set in one component's service and accessed from another component's service. Services help avoid direct communication between sibling components.

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

Angular 7

• The service is a class contains re-usable code (business logic, validations, calculations etc.), which can be
called in one or more components. If you place the re-usable set of properties and methods as a service
class, it can be called from any component or any other service in the entire application.
• We must decorate the service class with “@Injectable()” decorator, to make the service accessible from any
other component. You can import “@Injectable” decorator from “@angular/core” package.
• We must use “@Inject()” decorator, to request angular to create an object for the service class. Then the
angular framework will automatically creates an object for the service class and passes the object as
argument for your component’s constructor; you can receive it into a reference variable in the constructor.
You can use “@Inject” only in the constructor of component. To make the reference variable as member of
the component class, add “private” or “public” keyword at left side of the reference variable in the
constructor.
• In realtime, all the CRUD operations (Ajax calls) are created in the service; the same is called in the
component class, whenever required.

Steps to handle event:

• Create Service:

import { Injectable } from “@angular/core”;

@Injectable( )

class Serviceclassname

Methods here

• Add service as provider in the component:

@Component( { …, providers: [ Serviceclassname ] } )

class ComponentClassname

D. Harsha Vardhan (UI Expert) P a g e 201 | 454


Angular 7

• (or) Add service as provider in the module:

@NgModule( { providers: [ Serviceclassname ] } )

class ModuleClassname

• Get the instance of service using dependency injection:

import { Inject } from “@angular/core”;

@Component( { … } )

class ComponentClassname

constructor(@Inject(Serviceclassname) variable : Serviceclassname)

Services - Example

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

cd c:\angular\app1

ng g class User

ng g service Login

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 202 | 454


Angular 7

c:\angular\app1\src\app\app.module.ts

D. Harsha Vardhan (UI Expert) P a g e 203 | 454


Angular 7

c:\angular\app1\src\app\user.ts

c:\angular\app1\src\app\login.service.ts

D. Harsha Vardhan (UI Expert) P a g e 204 | 454


Angular 7

c:\angular\app1\src\app\app.component.ts

c:\angular\app1\src\app\app.component.html

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:

D. Harsha Vardhan (UI Expert) P a g e 205 | 454


Angular 7

http://localhost:4200

Sharing Data using Services


• We can’t share data among sibling components directly; but we can do it by using service.
• We can set data from component1 to service; Then the component2 can access data from service.

Sharing Data using Services - Example

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

D. Harsha Vardhan (UI Expert) P a g e 206 | 454


Angular 7

cd c:\angular\app1

ng g component India

ng g component Usa

ng g service Population

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 207 | 454


Angular 7

c:\angular\app1\src\app\app.module.ts

c:\angular\app1\src\app\population.service.ts

c:\angular\app1\src\app\app.component.ts

c:\angular\app1\src\app\app.component.html

D. Harsha Vardhan (UI Expert) P a g e 208 | 454


Angular 7

c:\angular\app1\src\app\india\india.component.ts

c:\angular\app1\src\app\india\india.component.html

c:\angular\app1\src\app\usa\Usa.component.ts

D. Harsha Vardhan (UI Expert) P a g e 209 | 454


Angular 7

c:\angular\app1\src\app\usa\Usa.component.html

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

• Directive is a class, that can be invoked (called) through an attribute of a tag in the template.
• Directive provides additional functionality for the html element.
• For example, "ngIf" directive checks the condition, displays the element if the condition is TRUE; and
removes the element if the condition is false.
• The "ElementRef" class represents the element, in which the directive is invoked.
• Directive can receive values from the element using @Input() decorator.
• Directive can add events to the element by using @HostListener() decorator.

D. Harsha Vardhan (UI Expert) P a g e 210 | 454


Angular 7

• We can communicate between the component to the directive, using @ViewChild decorator in the
component.

Steps for Working with Directives


• Create directive:

@Directive( { selector: "[directiveattributename]" } )

class directiveclassname

constructor(@Inject(ElementRef) referencename : ElementRef)

@Input() directiveproperty : datatype;

@HostListener("eventname")

methodname( )

• Add directive to the module:

@NgModule( { …, declarations: [ …, directiveclassname] } )

class moduleclassname

• Invoke directive from html tag:

<tag directiveattributename directiveproperty=" value "> </tag>

Custom Directives - Example

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

cd c:\angular\app1

D. Harsha Vardhan (UI Expert) P a g e 211 | 454


Angular 7

ng g directive Sample

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 212 | 454


Angular 7

c:\angular\app1\src\styles.css

c:\angular\app1\src\app\app.module.ts

c:\angular\app1\src\app\app.component.ts

D. Harsha Vardhan (UI Expert) P a g e 213 | 454


Angular 7

c:\angular\app1\src\app\app.component.html

c:\angular\app1\src\app\sample.directive.ts

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

D. Harsha Vardhan (UI Expert) P a g e 214 | 454


Angular 7

• Pipes transform the value into “user-expected format”.


• Pipes are invoked in expressions (interpolation binding), through pipe ( | ) symbol.
Syntax: {{ property | pipe }}

List of Built-in Pipes in Angular 2+


1. uppercase
2. lowercase
3. slice
4. number
5. currency
6. percent
7. date
8. json

Pipes - Example

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

cd c:\angular\app1

D. Harsha Vardhan (UI Expert) P a g e 215 | 454


Angular 7

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 216 | 454


Angular 7

c:\angular\app1\src\styles.css

c:\angular\app1\src\app\app.module.ts

c:\angular\app1\src\app\app.component.ts

c:\angular\app1\src\app\app.component.html

D. Harsha Vardhan (UI Expert) P a g e 217 | 454


Angular 7

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

D. Harsha Vardhan (UI Expert) P a g e 218 | 454


Angular 7

D. Harsha Vardhan (UI Expert) P a g e 219 | 454


Angular 7

Custom Pipes
• Custom pipes are the user-defined pipes.
• Custom pipe must be a class that has @Pipe( ) decorator and implements “PipeTransform” interface.
• The “PipeTransform” interface has “transform” method, which must be implemented in your pipe class.
• The “transform” method will be executed automatically, when the pipe is invoked in the expression
(through pipe ( | ) symbol).
• The “transform” method receive the input value as argument, do process, and return the result value, which
will be displayed in the output.
Syntax to call pipe: {{ property | pipe }}

Syntax of Custom Pipe Class


import { Pipe, PipeTransform } from “@angular/core”;

@Pipe( { name: “namehere” } )

class custompipeclassname implements PipeTransform

transform(value: datatype) : returndatatype

//do something the value here

return (modified value);

Add Pipe to the module

@NgModule( { …, declarations: [ custompipeclassname ], … } )

class moduleclassname

Invoke the pipe in the template


{{componentproperty | pipename}}

D. Harsha Vardhan (UI Expert) P a g e 220 | 454


Angular 7

Custom Pipes - Example

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

cd c:\angular\app1

ng g pipe Duration

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 221 | 454


Angular 7

c:\angular\app1\src\styles.css

c:\angular\app1\src\app\app.module.ts

c:\angular\app1\src\app\app.component.ts

D. Harsha Vardhan (UI Expert) P a g e 222 | 454


Angular 7

c:\angular\app1\src\app\app.component.html

c:\angular\app1\src\app\duration.pipe.ts

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

D. Harsha Vardhan (UI Expert) P a g e 223 | 454


Angular 7

Template Driven Forms


• Template Driven Forms are suitable for development of simple forms with limited no. of fields and simple
validations.
• In these forms, each field is represented as a property in the component class.
• Validations rules are defined in the template, using “html 5” attributes. Validation messages are displayed
using “validation properties” of angular.
• “FormsModule” should be imported from “@angular/forms” package.

HTML 5 attributes for validations:

o required=”required” : Field is mandatory

o minlength=”n” : Minimum no. of characters

o pattern=”reg exp” : Regular expression

Validation Properties:

o untouched

▪ true : Field is not focused.


▪ false : Field is focused.

o touched

▪ true : Field is focused.


▪ false : Field is not focused.

o pristine

▪ true : Field is not modified by the user.


▪ false : Field is modified by the user.

o dirty

▪ true : Field is modified by the user.


▪ false : Field is not modified by the user.

o valid

▪ true : Field value is valid.


▪ false : Field value is invalid

o invalid

▪ true : Field value is invalid.


▪ false : Field value is valid.

o errors : Represents the list of errors of the field.

▪ required : true / false


▪ minlength : true / false

D. Harsha Vardhan (UI Expert) P a g e 224 | 454


Angular 7

▪ pattern : true / false


▪ number : true / false
▪ email : true / false
▪ url : true / false

Sl. Description Regular Expression


No
1 Digits only ^[0-9]*$
2 Alphabets only ^[a-zA-Z ]*$
3 Indian Mobile Number ^[789]\d{9}$
4 Email \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
5 Usernames: Alphabets, Digits and ([A-Za-z0-9-]+)
Hyphens only
6 Passwords: 6 to 15 characters; ((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15})
atleast one upper case letter, one
lower case letter and one digit

Template Driven Forms - Example


• We are going to create a sample template driven form with validations.
Fields:

o Firstname

o Lastname

o Email

o Amount

o Gender

o Country

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

cd c:\angular\app1

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 225 | 454


Angular 7

c:\angular\app1\src\styles.css

D. Harsha Vardhan (UI Expert) P a g e 226 | 454


Angular 7

c:\angular\app1\src\app\app.module.ts

c:\angular\app1\src\app\app.component.ts

D. Harsha Vardhan (UI Expert) P a g e 227 | 454


Angular 7

c:\angular\app1\src\app\app.component.html

D. Harsha Vardhan (UI Expert) P a g e 228 | 454


Angular 7

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

D. Harsha Vardhan (UI Expert) P a g e 229 | 454


Angular 7

Reactive Forms (or) Model Driven Forms


• Reactive Forms (or) Model Driven Forms are new types of forms in angular, which are suitable for creating
large forms with many fields and complex validations.
• In these forms, each field is represented as “FormControl” and group of controls is represented as
“FormGroup”.
• “ReactiveFormsModule” should be imported from “@angular/forms” package.
• Validation rules are defined in the component using "Validators" object of angular and validation messages
are displayed in the template using "validation properties" of angular.

Validations in Reactive Forms:

o Validators.required : Field is mandatory


o Validators.minLength : Minimum no. of characters
o Validators.maxLength : Maximum no. of characters
o Validators.pattern : Regular expression

Validation Properties:

D. Harsha Vardhan (UI Expert) P a g e 230 | 454


Angular 7

o untouched

▪ true : Field is not focused.


▪ false : Field is focused.

o touched

▪ true : Field is focused.


▪ false : Field is not focused.

o pristine

▪ true : Field is not modified by the user.


▪ false : Field is modified by the user.

o dirty

▪ true : Field is modified by the user.


▪ false : Field is not modified by the user.

o valid

▪ true : Field value is valid.


▪ false : Field value is invalid

o invalid

▪ true : Field value is invalid.


▪ false : Field value is valid.

o errors : Represents the list of errors of the field.

▪ required : true / false


▪ minlength : true / false
▪ maxlength : true / false
▪ pattern : true / false

Reactive Forms - Example


• We are going to create a sample reactive form with validations.

Fields:

o Firstname

o Lastname

o Email

o Amount

o Gender

o Country

D. Harsha Vardhan (UI Expert) P a g e 231 | 454


Angular 7

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

cd c:\angular\app1

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 232 | 454


Angular 7

c:\angular\app1\src\styles.css

c:\angular\app1\src\app\app.module.ts

c:\angular\app1\src\app\app.component.ts

D. Harsha Vardhan (UI Expert) P a g e 233 | 454


Angular 7

c:\angular\app1\src\app\app.component.html

D. Harsha Vardhan (UI Expert) P a g e 234 | 454


Angular 7

D. Harsha Vardhan (UI Expert) P a g e 235 | 454


Angular 7

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

• The “Routing” concept is used to create page navigation in angular 2+ applications.


• “Routing” includes the process of mapping between the “route (url)” and corresponding component. Ex:
o http://localhost:8080/home ➔ HomeComponent

o http://localhost:8080/about ➔ AboutComponent

• The “@angular/router” package provides essential API to create routing.


• Angular 2+ supports two types of routing.
1. Hash-less routing Ex: /home

D. Harsha Vardhan (UI Expert) P a g e 236 | 454


Angular 7

2. Hash routing Ex: #/home

Steps for working with Routing


• Import “@angular/router” package in “package.json” file:
“dependencies”:
{
“@angular/router”: “latest”
}

• Set the base location of the application on server:


<base href=”/”>

• Import “Router” from “@angular/router” package:


Import { Routes } from “@angular/router”;

• Create routes:
var variable1 : Routes = [
{ path: “path here”, component: ComponentClassName },
{ path: “path here”, component: ComponentClassName },
….
];

• Import “RouterModule” from “@angular/router” package:


Import { RoutesModule} from “@angular/router”;

• Combine “your routes” and “RouterModule”:


var variable2 = RouterModule.forRoot(variable1, { useHash: true/false } );

• Import both “routes” and “RouterModule” in “AppModule”:


@NgModule( { …, imports: [ …, variable2 ] } )
class AppModule( )
{
}

• Create hyperlink to route:

<a routerLink=”/path”>Link text</a>

• Create placeholder to display route content:


<router-outlet>
</router-outlet>

D. Harsha Vardhan (UI Expert) P a g e 237 | 454


Angular 7

Routing - Example

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

cd c:\angular\app1

ng g component Home

ng g component About

ng g component Contact

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 238 | 454


Angular 7

c:\angular\app1\src\styles.css

c:\angular\app1\src\app\app.module.ts

D. Harsha Vardhan (UI Expert) P a g e 239 | 454


Angular 7

c:\angular\app1\src\app\app.component.ts

c:\angular\app1\src\app\app.component.html

c:\angular\app1\src\app\home\home.component.ts

c:\angular\app1\src\app\home\home.component.html

D. Harsha Vardhan (UI Expert) P a g e 240 | 454


Angular 7

c:\angular\app1\src\app\about\about.component.ts

c:\angular\app1\src\app\about\about.component.html

c:\angular\app1\src\app\contact\contact.component.ts

c:\angular\app1\src\app\contact\contact.component.html

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:

D. Harsha Vardhan (UI Expert) P a g e 241 | 454


Angular 7

http://localhost:4200

Click on “About”.

Click on “Contact”.

D. Harsha Vardhan (UI Expert) P a g e 242 | 454


Angular 7

Route Parameters
• You can pass parameters to the route.
• Route parameter is represented as “:parametername” syntax.
• You can get the value of the parameter in the component using “ActivatedRoute” service.

Steps for Working with Route Parameters


• Create parameter in the route:

{ path: "pathname/:parametername", component: ComponentClassname }

• Import the "ActivatedRoute" service:

import { ActivatedRoute } from "@angular/router";

• Get an object of "ActivatedRoute" service:

constructor(@Inject(ActivatedRoute) private route : ActivatedRoute)

• Get the value of parameter:

this.route.snapshot.params["parametername"]

D. Harsha Vardhan (UI Expert) P a g e 243 | 454


Angular 7

• (or) Get the value of parameter with updates:

this.route.params.subscribe(params =>

params["parametername"]

});

Route Parameters - Example

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

cd c:\angular\app1

ng g component Home

ng g component About

ng g component Contact

ng g component Products

ng g class Product

ng g service Products

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 244 | 454


Angular 7

c:\angular\app1\src\styles.css

c:\angular\app1\src\product.ts

D. Harsha Vardhan (UI Expert) P a g e 245 | 454


Angular 7

c:\angular\app1\src\products.service.ts

c:\angular\app1\src\app\app.module.ts

D. Harsha Vardhan (UI Expert) P a g e 246 | 454


Angular 7

c:\angular\app1\src\app\app.component.ts

c:\angular\app1\src\app\app.component.html

D. Harsha Vardhan (UI Expert) P a g e 247 | 454


Angular 7

c:\angular\app1\src\app\home\home.component.ts

c:\angular\app1\src\app\home\home.component.html

c:\angular\app1\src\app\about\about.component.ts

c:\angular\app1\src\app\about\about.component.html

c:\angular\app1\src\app\contact\contact.component.ts

D. Harsha Vardhan (UI Expert) P a g e 248 | 454


Angular 7

c:\angular\app1\src\app\contact\contact.component.html

c:\angular\app1\src\app\products\products.component.ts

D. Harsha Vardhan (UI Expert) P a g e 249 | 454


Angular 7

c:\angular\app1\src\app\products\products.component.html

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

D. Harsha Vardhan (UI Expert) P a g e 250 | 454


Angular 7

Click on “Apple”.

D. Harsha Vardhan (UI Expert) P a g e 251 | 454


Angular 7

Click on “Google”.

Child Routes
• Route can have child routes up to unlimited no. of nested levels.
• Ex: "Funds Transfer" menu has "Transfer", "Add Payee", "Activate Payee" etc.

Steps for Working with Child Routes


• Create Child Routes:

{ path: "parentpath ", component: ComponentClassname, children: [

{ path: "childpath ", component: ComponentClassname },

{ path: "childpath ", component: ComponentClassname },

]}

• Create hyperlink for the child route:

<a href="/parentpath/childpath">Link text</a>

• Create router outlet for child routes (in the parent route component's template):

<router-outlet> </router-outlet>

D. Harsha Vardhan (UI Expert) P a g e 252 | 454


Angular 7

Child Routes - Example

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

cd c:\angular\app1

ng g component OnlineShopping

ng g component Appliances

ng g component Electronics

ng g component Fashion

ng g component Furniture

ng g component Lighting

ng g component Mobiles

ng g component Laptops

ng g component Men

ng g component Women

ng g component Furniture

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 253 | 454


Angular 7

c:\angular\app1\src\styles.css

c:\angular\app1\src\app\app.module.ts

D. Harsha Vardhan (UI Expert) P a g e 254 | 454


Angular 7

D. Harsha Vardhan (UI Expert) P a g e 255 | 454


Angular 7

c:\angular\app1\src\app\app.component.ts

c:\angular\app1\src\app\app.component.html

c:\angular\app1\src\app\online-shopping\online-shopping.component.ts

c:\angular\app1\src\app\online-shopping\online-shopping.component.html

D. Harsha Vardhan (UI Expert) P a g e 256 | 454


Angular 7

c:\angular\app1\src\app\appliances\appliances.component.ts

c:\angular\app1\src\app\appliances\appliances.component.html

c:\angular\app1\src\app\electronics\electronics.component.ts

c:\angular\app1\src\app\electronics\electronics.component.html

D. Harsha Vardhan (UI Expert) P a g e 257 | 454


Angular 7

c:\angular\app1\src\app\fashion\fashion.component.ts

c:\angular\app1\src\app\fashion\fashion.component.html

c:\angular\app1\src\app\furniture\furniture.component.ts

D. Harsha Vardhan (UI Expert) P a g e 258 | 454


Angular 7

c:\angular\app1\src\app\furniture\furniture.component.html

c:\angular\app1\src\app\lighting\lighting.component.ts

c:\angular\app1\src\app\lighting\lighting.component.html

c:\angular\app1\src\app\mobiles\mobiles.component.ts

D. Harsha Vardhan (UI Expert) P a g e 259 | 454


Angular 7

c:\angular\app1\src\app\mobiles\mobiles.component.html

c:\angular\app1\src\app\laptops\laptops.component.ts

c:\angular\app1\src\app\laptops\laptops.component.html

c:\angular\app1\src\app\men\men.component.ts

c:\angular\app1\src\app\men\men.component.html

D. Harsha Vardhan (UI Expert) P a g e 260 | 454


Angular 7

c:\angular\app1\src\app\women\women.component.ts

c:\angular\app1\src\app\women\women.component.html

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

D. Harsha Vardhan (UI Expert) P a g e 261 | 454


Angular 7

D. Harsha Vardhan (UI Expert) P a g e 262 | 454


Angular 7

Click on “Electronics”.

D. Harsha Vardhan (UI Expert) P a g e 263 | 454


Angular 7

Click on “Mobiles”.

• The Guard is a service that executes at the specified situation while angular is navigating from one route to
another route.
• Angular mainly supports two types of Guards:
o CanActivate: Executes before entering into a route.

o CanDeactivate: Executes before leaving a route.

D. Harsha Vardhan (UI Expert) P a g e 264 | 454


Angular 7

CanActivate
• The "CanActivate" Guard executes before entering into a route.
• Process: User clicks on the hyperlink → Identify the route → CanActivate Guard → Navigate to the Route
→ Corresponding component.
• This guard can be created by implementing "CanActivate" interface.
• The "CanActivate" interface has a method called "canActivate". This method must return a boolean value,
which indicates whether the route can be navigated or not. If we return "true", the route will be navigated;
if we return "false", the route navigation will be stopped.
• It can receive an argument of "ActivatedRouteSnapshot" type, which represents the current state of the
route.

Steps for Working with CanActivate


• Import "CanActivate" interface from "@angular/router" package:

import { CanActivate, ActivatedRouteSnapshot } from "@angular/router";

• Create a Service that implements "CanActivate" interface:

class Serviceclassname implements CanActivate

canActivate(route: ActivatedRouteSnapshot): boolean

return true / false;

D. Harsha Vardhan (UI Expert) P a g e 265 | 454


Angular 7

• Add service to the module:

@NgModule( { …, providers: [ Serviceclassname ] } )

class moduleclassname

• Add guard to the route:

{ path: "path here", component: ComponentClassname, canActivate: [ Serviceclassname ] }

CanActivate - Example

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

cd c:\angular\app1

ng g component OnlineShopping

ng g component Appliances

ng g component Electronics

ng g component Fashion

ng g component Furniture

ng g component Lighting

ng g component Mobiles

ng g component Laptops

ng g component Men

ng g component Women

ng g component Furniture

ng g component Login

ng g service LoginStatus

ng g service LoginAuth

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 266 | 454


Angular 7

c:\angular\app1\src\styles.css

D. Harsha Vardhan (UI Expert) P a g e 267 | 454


Angular 7

c:\angular\app1\src\app\app.module.ts

D. Harsha Vardhan (UI Expert) P a g e 268 | 454


Angular 7

c:\angular\app1\src\app\login-status.service.ts

c:\angular\app1\src\app\login-auth.service.ts

D. Harsha Vardhan (UI Expert) P a g e 269 | 454


Angular 7

c:\angular\app1\src\app\login\login.component.ts

D. Harsha Vardhan (UI Expert) P a g e 270 | 454


Angular 7

c:\angular\app1\src\app\login\login.component.html

c:\angular\app1\src\app\app.component.ts

c:\angular\app1\src\app\app.component.html

c:\angular\app1\src\app\online-shopping\online-shopping.component.ts

D. Harsha Vardhan (UI Expert) P a g e 271 | 454


Angular 7

c:\angular\app1\src\app\online-shopping\online-shopping.component.html

c:\angular\app1\src\app\appliances\appliances.component.ts

c:\angular\app1\src\app\appliances\appliances.component.html

c:\angular\app1\src\app\electronics\electronics.component.ts

D. Harsha Vardhan (UI Expert) P a g e 272 | 454


Angular 7

c:\angular\app1\src\app\electronics\electronics.component.html

c:\angular\app1\src\app\fashion\fashion.component.ts

c:\angular\app1\src\app\fashion\fashion.component.html

D. Harsha Vardhan (UI Expert) P a g e 273 | 454


Angular 7

c:\angular\app1\src\app\furniture\furniture.component.ts

c:\angular\app1\src\app\furniture\furniture.component.html

c:\angular\app1\src\app\lighting\lighting.component.ts

c:\angular\app1\src\app\lighting\lighting.component.html

c:\angular\app1\src\app\mobiles\mobiles.component.ts

D. Harsha Vardhan (UI Expert) P a g e 274 | 454


Angular 7

c:\angular\app1\src\app\mobiles\mobiles.component.html

c:\angular\app1\src\app\laptops\laptops.component.ts

c:\angular\app1\src\app\laptops\laptops.component.html

c:\angular\app1\src\app\men\men.component.ts

D. Harsha Vardhan (UI Expert) P a g e 275 | 454


Angular 7

c:\angular\app1\src\app\men\men.component.html

c:\angular\app1\src\app\women\women.component.ts

c:\angular\app1\src\app\women\women.component.html

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

D. Harsha Vardhan (UI Expert) P a g e 276 | 454


Angular 7

D. Harsha Vardhan (UI Expert) P a g e 277 | 454


Angular 7

Click on “Electronics”.

D. Harsha Vardhan (UI Expert) P a g e 278 | 454


Angular 7

Enter the username as “admin” and password as “manager”. Click on “Login”.

D. Harsha Vardhan (UI Expert) P a g e 279 | 454


Angular 7

Click on “Electronics” now.

D. Harsha Vardhan (UI Expert) P a g e 280 | 454


Angular 7

D. Harsha Vardhan (UI Expert) P a g e 281 | 454


Angular 7

CanDeactivate
• The "CanDeactivate" Guard executes before leaving from a route.
• This guard can be created by implementing "CanDeactivate" interface.
• The "CanDeactivate" interface has a method called "canDeactivate". This method must return a boolean
value, which indicates whether the route can be leave or not. If we return "true", the route will be left; if we
return "false", the route navigation will be stopped.
• It can receive an argument of an user-defined interface type, , which represents the current component.

Steps for Working with CanDeactive


• Import "CanDeactivate" interface from "@angular/router" package:

import { CanDeactivate } from "@angular/router";

• Create the interface for CanDeactive Guard:

interface interfacename

canNavigate: boolean;

• Create a Service that implements "CanDeactivate" interface:

class Serviceclassname implements CanDeactivate<interfacename>

canDeactivate(component: interfacename): boolean

return true / false;

• Add service to the module:

@NgModule( { …, providers: [ Serviceclassname ] } )

class moduleclassname

D. Harsha Vardhan (UI Expert) P a g e 282 | 454


Angular 7

• Add guard to the route:

{ path: "path here", component: ComponentClassname, canDeactivate: [ Serviceclassname ] }

CanDeactivate - Example

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

cd c:\angular\app1

ng g component Home

ng g component About

ng g component Contact

ng g class CanComponentDeactivate

ng g service CanDeactiveGuard

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 283 | 454


Angular 7

c:\angular\app1\src\styles.css

c:\angular\app1\src\app\can-component-deactivate.ts

c:\angular\app1\src\app\can-deactivate-guard.service.ts

D. Harsha Vardhan (UI Expert) P a g e 284 | 454


Angular 7

c:\angular\app1\src\app\app.module.ts

c:\angular\app1\src\app\app.component.ts

D. Harsha Vardhan (UI Expert) P a g e 285 | 454


Angular 7

c:\angular\app1\src\app\app.component.html

c:\angular\app1\src\app\home\home.component.ts

D. Harsha Vardhan (UI Expert) P a g e 286 | 454


Angular 7

c:\angular\app1\src\app\home\home.component.html

c:\angular\app1\src\app\about\about.component.ts

c:\angular\app1\src\app\about\about.component.html

c:\angular\app1\src\app\contact\contact.component.ts

D. Harsha Vardhan (UI Expert) P a g e 287 | 454


Angular 7

c:\angular\app1\src\app\contact\contact.component.html

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

Type some firstname and lastname and click on “About”.

D. Harsha Vardhan (UI Expert) P a g e 288 | 454


Angular 7

Click on “OK”.

Click on “Home”.

D. Harsha Vardhan (UI Expert) P a g e 289 | 454


Angular 7

Enter some firstname and lastname and click on “Save”.

Click on “About”.

D. Harsha Vardhan (UI Expert) P a g e 290 | 454


Angular 7

Deployment to Java

Setting-up Environment for Java


• Install Java from “https://java.com/en/download”.
• Add “C:\Program Files\Java\jdk1.8.0_172\bin” as “Path” of system variables.
• Add “JAVA_HOME” with “C:\Program Files\Java\jdk1.8.0_172” in system variables.
• Download tomcat from “https://tomcat.apache.org/download-90.cgi”. Click on “zip” in “Core”. You will get
a file called “apache-tomcat-9.0.7.zip”. Right click on “apache-tomcat-9.0.7.zip” and click on “Extract All”.
Copy all contents of the extracted folder into “c:\tomcat” folder.
• Open Command Prompt and enter the following commands:
cd c:\tomcat\bin

startup.bat

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 291 | 454


Angular 7

c:\angular\app1\src\app\app.module.ts

D. Harsha Vardhan (UI Expert) P a g e 292 | 454


Angular 7

c:\angular\app1\src\app\app.component.ts

c:\angular\app1\src\app\app.component.html

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng build --prod

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

D. Harsha Vardhan (UI Expert) P a g e 293 | 454


Angular 7

• Copy all files from “c:\angular\app1\dist” folder to “c:\tomcat\webapps\ROOT”.

• Open the browser and enter the following URL:


http://localhost:8080/index.html

D. Harsha Vardhan (UI Expert) P a g e 294 | 454


Angular 7

Deployment to .NET

Setting-up Environment for .NET


• Install Visual Studio Community 2017 from “https://www.visualstudio.com”.
• Open Visual Studio 2017. Click on “File” – “New” – “Project” – “Visual C#” – “ASP.NET Web Application (.NET
Framework)”. Enter the project name “WebApplication1”. Enter the location as “c:\angular”. Click on “OK”.

• Click on “Empty”. Click on OK.

D. Harsha Vardhan (UI Expert) P a g e 295 | 454


Angular 7

Creating Application
• Open Command Prompt and enter the following commands:
cd c:\angular

ng new app1

c:\angular\app1\package.json

D. Harsha Vardhan (UI Expert) P a g e 296 | 454


Angular 7

c:\angular\app1\src\app\app.module.ts

c:\angular\app1\src\app\app.component.ts

D. Harsha Vardhan (UI Expert) P a g e 297 | 454


Angular 7

c:\angular\app1\src\app\app.component.html

Executing the application:


• Open Command Prompt and enter the following commands:
cd c:\angular\app1

ng build --prod

ng serve

• Open the browser and enter the following URL:


http://localhost:4200

• Copy all files from “c:\angular\app1\dist” folder to “Solution Explorer”.

D. Harsha Vardhan (UI Expert) P a g e 298 | 454


Angular 7

• Right click on “index.html” and click on “View in Browser”.

• AJAX (Asynchronous JavaScript And Xml) is not a language, but it is a “concept”, which is used to “send a
background request from browser to server” and also “get background response from server to browser”,
without refreshing (reloading) the web page in the browser.
• AJAX allows us to interact with the server and get some data from server, without refreshing the full web
page.
• Ex: Facebook like button, comments, IRCTC search trains.

D. Harsha Vardhan (UI Expert) P a g e 299 | 454


Angular 7

Execution Flow of AJAX

Advantages of AJAX
• Executes faster
• Less burden on browser (client) and server
• Better user experience.

Types of AJAX Request


• Get : Used to retrieve / search data from server

• Post : Used to insert data to server.

• Put : Used to update data on server.

• Delete : Used to delete data from server

“@angular/common/http” package
• The “@angular/common/http” package provides necessary services to send ajax request to server and get
ajax response from server.

Steps for working with “@angular/common/http” package:


• Import “@angular/common” package in “package.json”:
“dependencies”:
{
“@angular/common:”: “latest”
}

• Import “HttpClientModule” module:


import { HttpClientModule, HttpClient } from “@angular/common/http”;

• Import “HttpClientModule” in “AppModule”:


@NgModule( { …, imports: [ …, HttpClientModule ] } )
class AppModule

D. Harsha Vardhan (UI Expert) P a g e 300 | 454

You might also like