0% found this document useful (0 votes)
4 views

unit_5-angular-routing-and-application-development

This document provides a comprehensive guide on Angular routing and application development, covering topics such as server setup, component creation, route definition, and navigation. It explains how to implement routing in an Angular application, including the use of route parameters, wildcard routes, and route guards for access control. Additionally, it discusses advanced concepts like API calls, CORS, and lazy loading to enhance application performance.

Uploaded by

shivam.gperi
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)
4 views

unit_5-angular-routing-and-application-development

This document provides a comprehensive guide on Angular routing and application development, covering topics such as server setup, component creation, route definition, and navigation. It explains how to implement routing in an Angular application, including the use of route parameters, wildcard routes, and route guards for access control. Additionally, it discusses advanced concepts like API calls, CORS, and lazy loading to enhance application performance.

Uploaded by

shivam.gperi
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/ 14

Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

Angular Routing and Application Development


5.1 Server Setup, Importing the Router Module, Displaying the Route Contents,
Navigating Within the Application, Wildcards and Defaults

Generate an application with routing enabled


 The following command uses the Angular CLI to generate a basic Angular application with an
application routing module, called AppRoutingModule, which is an NgModule where you can configure
your routes.
 The application name in the following example is routing-app.
content_copyng new routing-app --routing --defaults

Adding components for routing


 To use the Angular router, an application needs to have at least two components so that it can navigate
from one to the other.
 To create a component using the CLI, enter the following at the command line where first is the name of
your component:
content_copyng generate component first
 Repeat this step for a second component but give it a different name. Here, the new name is second.
Content_copyng generate component second
 The CLI automatically appends Component, so if you were to write first-component, your component
would be FirstComponentComponent.
<base href>
 This guide works with a CLI-generated Angular application. If you are working manually, make sure
that you have <base href="/"> in the <head> of your index.html file.
 This assumes that the app folder is the application root, and uses "/".

Importing your new components


 To use your new components, import them into AppRoutingModule at the top of the file, as follows:

AppRoutingModule (excerpt)

content_copyimport { FirstComponent } from './first/first.component';

import { SecondComponent } from './second/second.component';

Defining a basic route

 There are three fundamental building blocks to creating a route.


 Import the AppRoutingModule into AppModule and add it to the imports array.

Prepared By: Department of Computer Engineering Page 1


Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

 The Angular CLI performs this step for you. However, if you are creating an application manually or
working with an existing, non-CLI application, verify that the imports and configuration are correct. The
following is the default AppModule using the CLI with the --routing flag.

Default CLI AppModule with routing

content_copyimport { BrowserModule } from '@angular/platform-browser';


import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module'; // CLI imports AppRoutingModule
import { AppComponent } from './app.component';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule // CLI adds AppRoutingModule to the AppModule's imports array
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

1. Import RouterModule and Routes into your routing module.

 The Angular CLI performs this step automatically. The CLI also sets up a Routes array for your routes
and configures the imports and exports arrays for @NgModule().
CLI application routing module

content_copyimport { NgModule } from '@angular/core';


import { Routes, RouterModule } from '@angular/router'; // CLI imports router
const routes: Routes = []; // sets up routes constant where you define your routes
// configures NgModule imports and exports
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

2. Define your routes in your Routes array.

 Each route in this array is a JavaScript object that contains two properties. The first property, path,
defines the URL path for the route.
 The second property, component, defines the component Angular should use for the corresponding path.

Prepared By: Department of Computer Engineering Page 2


Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

AppRoutingModule (excerpt)

content_copyconst routes: Routes = [


{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
];

3. Add your routes to your application.

 Now that you have defined your routes, add them to your application. First, add links to the two
components.
 Assign the anchor tag that you want to add the route to the routerLink attribute.
 Set the value of the attribute to the component to show when a user clicks on each link. Next, update
your component template to include <router-outlet>.
 This element informs Angular to update the application view with the component for the selected route.

Template with routerLink and router-outlet

content_copy<h1>Angular Router App</h1>


<!-- This nav gives you links to click, which tells the router which route to use (defined in the
routes constant in AppRoutingModule) -->
<nav>
<ul>
<li><a routerLink="/first-component" routerLinkActive="active"
ariaCurrentWhenActive="page">First Component</a></li>
<li><a routerLink="/second-component" routerLinkActive="active"
ariaCurrentWhenActive="page">Second Component</a></li>
</ul>
</nav>
<!-- The routed views render in the <router-outlet>-->
<router-outlet></router-outlet>

Route order

 The order of routes is important because the Router uses a first-match wins strategy when matching
routes, so more specific routes should be placed above less specific routes.
 List routes with a static path first, followed by an empty path route, which matches the default route.
 The wildcard route comes last because it matches every URL and the Router selects it only if no other
routes match first.
Getting route information

 Often, as a user navigates your application, you want to pass information from one component to
another.
 For example, consider an application that displays a shopping list of grocery items.

Prepared By: Department of Computer Engineering Page 3


Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

 Each item in the list has a unique id. To edit an item, users click an Edit button, which opens
an EditGroceryItem component. You want that component to retrieve the id for the grocery item so it can
display the right information to the user.
 Use a route to pass this type of information to your application components. To do so, you use the with
ComponentInputBinding feature with provide Router or the bindToComponentInputs option
of RouterModule.forRoot.

To get information from a route:

1. Add the withComponentInputBinding feature to the provideRouter method.


ProvideRouter feature

content_copyproviders: [
provideRouter(appRoutes, withComponentInputBinding()),
]

2. Update the component to have an Input matching the name of the parameter.The component
input (excerpt)

content_copy@Input()

set id(heroId: string) {

this.hero$ = this.service.getHero(heroId);

NOTE:
You can bind all route data with key, value pairs to component inputs: static or resolved route data,
path parameters, matrix parameters, and query parameters.
Setting up wildcard routes

 A well-functioning application should gracefully handle when users attempt to navigate to a part of your
application that does not exist.
 To add this functionality to your application, you set up a wildcard route. The Angular router selects this
route any time the requested URL doesn't match any router paths.
 To set up a wildcard route, add the following code to your routes definition.

AppRoutingModule (excerpt)

content_copy{ path: '**', component: <component-name> }

 The two asterisks, **, indicate to Angular that this routes definition is a wildcard route.
Prepared By: Department of Computer Engineering Page 4
Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

 For the component property, you can define any component in your application.
 Common choices include an application-specific PageNotFoundComponent, which you can define
to display a 404 page to your users; or a redirect to your application's main component.
 A wildcard route is the last route because it matches any URL. For more detail on why order matters for
routes, see Route order.

Displaying a 404 page

 To display a 404 page, set up a wildcard route with the component property set to the component you'd
like to use for your 404 page as follows:

AppRoutingModule (excerpt)

content_copyconst routes: Routes = [

{ path: 'first-component', component: FirstComponent },

{ path: 'second-component', component: SecondComponent },

{ path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page

];

 The last route with the path of ** is a wildcard route. The router selects this route if the requested URL
doesn't match any of the paths earlier in the list and sends the user to the PageNotFoundComponent.

5.2 Common Routing Requirements, Required Route Params, Optional Route Params

Required Parameters
 Required Route Parameters is used in pattern matching of the route so syntax should be correct in path .
 Prefer This Parameter when value is simple not complex and multiple parameters are not passed

Syntax
//Declaration
const appRoutes:Routes = [{path:employee/:id,component:abcComp}]
// Here id is added as required parameter //Implementation in Ts (typescript)
let id = 2 // It can be dynamic this.route.navigate(['employee',id])// Catching The Route Parameter in Ts
constructor (private route :ActivatedRoute){
}
let id = parseInt(this.route.snapshot.paraMap.get('id'))

Optional Parameter

Prepared By: Department of Computer Engineering Page 5


Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

 This Parameter is used when they are optional and we need to pass complex and multiple parameters.
 Optional parameter is not used in patter matching so we don’t need it to declare in routing path.

// Declaration
const appRoutes:Routes = [{path:employee,component:abcComp}]
// You dont need to set optional parameter in routing
//Implementationthis.route.navigate(['employee',{name:'ab'}]) // You can add multiple by using
,separated key for example {name:'ab',id:'1'}// Catching constructor (private route :ActivatedRoute){
}
let name = this.route.snapshot.paraMap.get('name')

Query Parameters
 They are used to pass complex parameters and they are not used in pattern matching so we don’t need it
to declare in routing path.

// Declaration
const appRoutes:Routes = [{path:employee,component:abcComp}]
// You dont need to set Query parameter in routing// Implementation in Ts
this.route.navigate(['employee'],{queryParams:{name:'a'}})//queryParamsHandling='Merge' or 'retain'
these options is also used to retain the parameters or to merge them // Catching in Ts constructor(private
route :ActivateRoute){
}
let name = this.route.snapshot.queryParamMap.get('name');

NavigationExtras
 This New Method Cam After Angular 7.2.0

//Declaration
const appRoutes:Routes = [{path:employee,component:abcComp}]
// You dont need to set Extras in routing//Implementation In Ts
this.route.navigate(['employee'],{state:{name:'A'}})//Catching in Ts constructor (private router :
Router){this.router.getCurrentNavigation().extras.state.name;
}// This works only in constructor it will not work on ngOnInit

Prepared By: Department of Computer Engineering Page 6


Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

5.3 Route Guards: Authenticated-Only Routes, Preventing Unload, Preloading Data Using
Resolve

What is Route Guard?


 In the traditional web application, we were checking users' access and permission using Authentication
and Authorization on the server side. If the user doesn’t have sufficient access or permission, we were
redirecting a user to the login page with an appropriate error message.
 Now a question comes to mind; how we will achieve this in Angular? I mean how will restrict a user to
access a certain area of the application without login/permission?
 That’s one of the scenarios where Route Guard comes into the picture.
 Route Guards help us to prevent users to access a certain area of the application that is not permitted or
has access to.
Type of Route Guard?
 Four types of Route guards are available in Angular. In this article, we will cover the “CanActivate”
Route guard and the rest will cover in subsequent articles.

1. CanActivate
2. CanActivateChild
3. CanDeactivate
4. CanLoad

 Please note that all Route guards have interfaces that need to be implemented in the component class.
 eg. “CanActivate” is an interface that has a method called “canActivate”

 Suppose we have multiple Route guards applied to a specific route then all route guards should return
true to navigate. If any route guard returns false then the navigation will be canceled.

Prepared By: Department of Computer Engineering Page 7


Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

 In the above screen, we have two route guards,

1. MemberAuthGaurd
2. DetailsAuthGuard

 So both route guards should return true. In case any of the route guards return false then “member”
navigation will not work.
 First, we will see the syntax/command used to create a route guard.
 Syntax : ng g g “name of the guard”

 Now we will create an angular application and implement RouteGuard to get hands-on experience.
Example
1. Create a new angular application,
2. Create Two components
3. Implement Routing
4. Create a new Auth service.
5. Create RouteGaurd
6. Configure Service in the RouteGuard
7. Configure

Prepared By: Department of Computer Engineering Page 8


Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

5.4 API/Server Calls and CORS


 The CORS stands for Cross-Origin Resource Sharing. That is exactly what we were doing. We
separated server and client that were running on different domains.
 We used localhost: 3000 for the server and localhost 4200 for our angular app.
 The client and server both wanted to talk with each other, but they were not on the same host.
 If they were on the same host, they could communicate without any issue. So, if the request is coming
from a different address, this gave us a so-called CORS error.
 In many modern web apps, we need to allow this. It is not a security issue; it is a wanted behavior.
 For this, we need to expose our server API for all possible clients, and this is done by setting the right
headers on the server-side response.
 CORS manages request from the external domain by using a set of newly created HTTP headers which
are as follows -
o Access-Control-Allow-Origin
o Access-Control-Allow-Credentials
o Access-Control-Allow-Headers
o Access-Control-Allow-Methods
o Access-Control-Expose-Headers
o Access-Control-Max-Age
o Access-Control-Request-Headers
o Access-Control-Request-Method
o Origin

5.5 Lazy Loading


 Lazy loading is the process of loading components, modules, or other assets of a website as they're
required.
 Since Angular creates a SPA (Single Page Application), all of its components are loaded at once. This
means that a lot of unnecessary libraries or modules might be loaded as well.
 As the application grows the load time will increase if everything is loaded at once. Lazy loading allows
Angular to load components and modules as and when they're needed.
 Lazy loading is a technology of angular that allows you to load JavaScript components when a specific
route is activated.
 It improves application load time speed by splitting the application into many bundles. When the user
navigates by the app, bundles are loaded as needed.
 Lazy loading helps to keep the bundle size small, which helps reduce load times.
 We must use the class decorator to create an Angular module @NgModule, and the decorator uses a
metadata object that defines the module.
 The main properties are:
o Import: Components of this module are used with Array with other modules.
o Declarations: It receives an array of the components.
o Export: Defines an array of components, directives, and pipes used by other modules.
Prepared By: Department of Computer Engineering Page 9
Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

o Provider: Declares services that are available to the entire application if it is a root module.
Example of a native root module:

import { BrowserModule } from '@angular/platform browser;


import { NgModule } from '@angular/core';
import { AppComponent} from './app.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
Announcement: [
AppComponent
],
import: [
browser module,
app routing module
],
Providers: [], //Os service declarados and Propried providers do modulo root ficum disponivism
toda a applicacao
bootstrap: [AppComponent] //define some or module root um bootstrap
})
export class AppModule { }

 In the above sample code, we have converted the AppModule class into an Angular module using the
@NgModule decorator.

Lazy Loading Basics


 In the lazy load Angular modules, use load children in your AppRoutingModule root configuration as
follows.

AppRoutingModule (excerpt)
content_copyconst routes: Routes = [
{
path: 'item',
loadChildren: () => import('./items/items.module').then(m => m.ItemModule)
}
];

Prepared By: Department of Computer Engineering Page 10


Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

 Add a route for the component in the lazy-loaded routing module.

Routing module for the lazy-loaded module

content_copyconst routes: Routes = [


{
path: '',
component: ItemsComponent
}
];

Steps to implement Lazy Loading in an Angular Project

Step 1:
Create a new Angular project,
ng new angular-lazy-loading

Step 2:
The purpose of independent routing is to handle all components with Angular lazy-loading modules.
ng g m lazy-loading-routing

Step 3:
Create a component called lazy-demo within the lazy-loading module,
ng g c lazy demode

Prepared By: Department of Computer Engineering Page 11


Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

Step 4:
Adding a link to the header will implement lazy loading.
app.component.html

<li class="nav-item">
<a class="nav-link" [routerLink]="['/lazy-loading']">
slow loading
</a>
</li>
Step 5:
Here we will lazily load the module using load children.
App-routing.module.ts

path: 'lazy-loading',
load children: () => import('./lazy-loading/lazy-loading.module')
.then(m => m.LazyLoadingModule)
},
Step 6:
Set the route in lazy-loading-routing.module.ts.
lazy-loading-routing.module.ts

import { NgModule } from '@angular/core';


import {RouterModule, Routes} from '@angular/router';
import { LazyDemoComponent } from './lazy-demo/lazy-demo.component';
const route: route = [
{ path: '', component: LazyDemoComponent }
];
@NgModule({
import: [routerModule. for child (route)],
export: [routermodule]
})
export class LazyLoadingRoutingModule { }

Prepared By: Department of Computer Engineering Page 12


Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

If above import option gives error, then try this,

import { LazyDemoComponent } from "E:/Pranam/Git Repository Projects/Angular-Lazy-Loading-


Example/src/app/lazy-demo/lazy-demo.component";

Run the application.

Go to the terminal and execute the "ng serve" command.

Now go to the browser https://localhost:4200.

Prepared By: Department of Computer Engineering Page 13


Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705

You will see that main.js is being served upon refreshing the browser. The Lazy Loading module is loaded only
when the root /lazy-loading is hit.

Prepared By: Department of Computer Engineering Page 14

You might also like