Lesson 11 Routing

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

Angular 4

Lesson 11—Routing

© Simplilearn. All rights reserved.


Learning Objectives

By the end of this lesson, you should be able to:

Describe how Angular helps to achieve Single Page Applications


(SPA) using routing

Define benefits of @NgModule

Identify multiple ways of accessing routes

Explain the process of routing lifecycle


Routing
Topic 1—Routers
What are Routers?

Angular Routers:

• Display the application component for the active URL

• Manage navigation from one component to the next

• Are often used in Single Page Applications (SPA)


Need for Routers

1 Routers segregate the application into different areas

2 Routers maintain the state in the application

3 Routers follow certain rules to protect areas of the app

The URL bar provides an edge to web applications over native applications.

• Routers permit you to reference states, bookmark them, and share them.
• In a good web application, an application state transition results in a URL change, and a
modification in the URL alters the transition state. A URL is a serialized router state.
Routing
Topic 2—Single Page Application (SPA)
Single Page Application (SPA)

SPA is a single page web application where you can:

• Retrieve your code (CSS, HTML, JavaScript) with a single page


load
• Navigate between pages without the need of refreshing the
entire page
Pros of Single Page Application (SPA)

There is no need to refresh the entire page. You can just load the part of the
No page
refresh
page that needs to be changed. Angular permits you to pre-load and cache all
pages, so you don’t require extra requests to download them.

Improved
user SPAs act as native applications, which are fast and responsive.
experience

Ability to With SPAs, all pages are already loaded, so they work even if the internet
work offline
connection is lost.
Cons of Single Page Application (SPA)

Complex to build You are required to write JavaScript, handle shared state
between pages, manage permissions, and more.

Slow initial load SPA is slow in the initial load as it needs to download more
resources when you open it.

JavaScript required SPA requires clients to have JavaScript enabled.


Building SPA with Angular Router

• Angular Router is an optional service that displays a distinct component view for a given URL.

• It is not a part of Angular core. It is in its own library package, @angular/router. You can import per
your requirement as any other Angular package.

import { RouterModule, Routes } from '@angular/router';


Routing
Topic 3—NgModule
NgModule

NgModule is a way to organize dependencies for the compiler and dependency injection (DI).

Main benefits of NgModule:

1 Dependency Injection

2 Lazy-load module with Router

3 Ahead of Time Compiler (AoT compiler)


NgModule
Module Feature
This is how the module file looks:

>_ training@localhost:~

@NgModule({
imports: [
RouterModule.forChild([…]),
CommonModule
],
providers: [
HomeService
],
declarations: [
HomeComponent
]
})
Export default class HomeModule{}
Routing
Topic 4—Router Basic
Router Basic

Main components used to configure routing:

Routers define the routes that your


application supports
1

RouterOutlet is where the page


2
content goes
RouterLink directive is used for
3
navigation
Router Basic—Define Routes

This is a mapping file where you can map components to their target URL.

>_ training@localhost:~

Const routes = [
{path: ‘’, redirectTo: ‘home’}, //Index router
{path: ‘home’, component: HomeComponent},
{path: ‘guards’, component: GuardsComponent},
{path: ‘resolver’, component: ResolverComponent},
{path: ‘preview’, component: PreviewComponent},
{path: ‘**’, component: E404Component //Fallback router
];
Router Basic—Register Root Router

This is where the Root Router gets registered.

>_ training@localhost:~

import {RouterModule} from ‘@angular/router’;


Const routes = [
………
];
@NgModule({
…….
imports: [
BrowserModule,
routerModule.forRoot(routes)
],
bootstrap: [AppComponent]
})
Export class AppModule{
}
Router Basic—Navigate to Link

routerLink Directive:

routerLink directive is used to bind a clickable HTML element to a route.

Click on an element with a routerLink directive that is bound to a string or


a link parameters array, which triggers a navigation.

>_ training@localhost:~

<a [routerLink]=“[‘/home’]”>Home</a>
<a [routerLink]=“[‘/guards’]”>Guards</a>
<a [routerLink]=“[‘/resolver’]”>Resolver</a>
<a [routerLink]=“[‘/preview’]”>Preview</a>
Router Basic—Rendering the Page

Router Outlet Directive:

Marks where the router displays a view

Acts as a placeholder that Angular dynamically fills based on the current router state

>_ training@localhost:~

<router-outlet></router-outlet>
Demo—Basic Routing

DEMO
Routing
Topic 5—Parameter Routing
Parameter Routing

• In an application, you often want to navigate to a specific resource.

• For example, you have a news website with many articles. Every article may have an ID, and there is

an article with ID 3. You may navigate to article 3 by visiting the URL:

/articles/3

• Similarly, to access an article with ID 4, you may use the URL:

/articles/4
Parameter Routing

This is the way to indicate the route path by adding a parameter to router configuration:

>_ training@localhost:~

export const routing=RouterModule.forRoot([


{path: '',component : HomeComponent},
{path: 'messages',component : MessagesComponent},
{path: 'photos/:id',component : PhotoDetailsComponent},
{path: 'photos',component : PhotosComponent},
{path: '**',component : NotFoundComponent}
]);
Demo—Parameter Routing

DEMO
Routing
Topic 6—Child Routes
Child Routes

Sometimes, when routes are accessible and viewed only within other routes, it is more relevant
to create them as child routes.

Example :

• There is a tabbed navigations section in the product details page that presents the
product overview by default.

• When the user clicks on the "Technical Specs" tab, the section shows the specs instead.
Declaration of Child Route

Example :

• In case the user clicks on the link of ID 3, show the user details page with the “overview”:
localhost:3000/user-details/3/overview

• When the user clicks on “user skills": localhost:3000/user-details/3/skills

• Here, overview and skills are child routes of user-details/:id. They are reachable only
within user details.
Child Routing Page

Example:

• In this page, both child one and two are child routes of component two.
Demo—Child Routing

DEMO
Routing
Topic 7—Router Lifecycle Hooks
Router Lifecycle Hooks

• Just like components go through a set of different phases during their


lifetime, a routing operation goes through different lifecycle stages.

• Each one is accessible from a different lifecycle hook which, just like
components, can be handled by implementing a specific interface in the
component subject of the routing action.
The CanActivate Hook

• The CanActivate hook, presented as a decorator annotating the component, is checked by the Router
right before it is instantiated.

• Its “set up” should be configured with a function that returns a Boolean value (or a
Promise-typed Boolean value) indicating whether the component should be finally
activated or not.

@CanActivate((next, prev) => boolean | Promise<boolean>)


The OnActivate Hook

• The OnActivate hook allows you to perform custom actions once the route navigation to the

component has been successfully accomplished.

• You can easily handle it by implementing a simple interface.

• These custom actions can even encompass asynchronous operations, in which case, you need

to return a Promise from the interface function.

• The route will only change once the Promise has been resolved.
The CanDeactivate and OnDeactivate Hooks

• The logic you use to determine whether the component you navigate to can be activated can also be

used when a user navigates from current component to another one elsewhere in your application.

• In case of the CanActivate hook, you must return a Boolean or a Promise resolving to a Boolean to

allow the navigation to proceed.

• When the CanDeactivate hook returns, or is resolved to true, the OnDeactivate hook is executed just

like the OnActivate hook after the navigation is accomplished.


Demo—Router Lifecycle Hooks

DEMO
Key Takeaways

Router of Angular enables navigation from one view to the next as


users perform application tasks.

NgModule is a way to organize your dependencies for the compiler


and Dependency Injection (DI).

Parameter routing and child routing are ways of accessing routers.

Angular uses a lifecycle hook to carry out actions when changing routes.
Quiz
QUIZ The ___________ directive substitutes the normal href property and makes it easier to
1 work with route links in Angular.

a. RouterLink

b. RouterRend

c. RouterLike

d. RouterLayer
QUIZ The ___________ directive substitutes the normal href property and makes it easier to
1 work with route links in Angular.

a. RouterLink

b. RouterRend

c. RouterLike

d. RouterLayer

The correct answer is a.


The RouterLink directive substitutes the normal href property and makes it easier to work with
route links in Angular.
QUIZ
Which statement does NOT apply to routers?
2

a. Routers are used to control navigation

b. Routers are often used in Single Page Applications (SPA)

c. Routers are used to connect to back end services

d. Routers maintain the state in the application


QUIZ
Which statement does NOT apply to routers?
2

a. Routers are used to control navigation

b. Routers are often used in Single Page Applications (SPA)

c. Routers are used to connect to back end services

d. Routers maintain the state in the application

The correct answer is c.


Routers are not used to connect to back end services.
QUIZ The router in Angular has been reworked to be simple, yet extensible. It will include
3 the following basic features:

a. Simple JSON-based Route Config

b. Optional Convention over Configuration

c. Static, Parameterized, and Splat Route Patterns

d. URL Unresolver

e. All of the above


QUIZ The router in Angular has been reworked to be simple, yet extensible. It will include
3 the following basic features:

a. Simple JSON-based Route Config

b. Optional Convention over Configuration

c. Static, Parameterized, and Splat Route Patterns

d. URL Unresolver

e. All of the above

The correct answer is a, b, and c


The router in Angular is simple, yet extensible. It includes simple JSON-based Routing Config,
optional Convention over Configuration and Static, Parameterized, and Splat Route Patterns.
Thank You

You might also like