Angular Router
Learn how Angular routing works and what code is required in page components to implement routing.
We'll cover the following
How routing works
The Angular Router handles the user’s request to navigate to a page within the application through the following steps:
- Reads the requested URL
- If the requested URL is defined, a URL redirect is applied
- Determines which state applies to the destination URL
- Authentication guards, if required, are activated (we’ll cover these a little later in this chapter)
- Data that is required for the router state is fully resolved
- Triggers the necessary Angular components required to display the page for the requested URL
- Manages the navigation between pages
- Repeats steps 1 to 7 when a new page is requested
With this understanding in place, let’s look at the different modules, components, and page elements required to manage this routing and navigation flow.
The elements required
In the context of an Ionic application, the Angular Router relies on some elements being in place:
- HTML
<base href>
tag - Router imports
- App Routing Module
- Router Outlet
Note: All of these elements are automatically generated by the Ionic CLI when creating a project from the command line.
The base href
tag
The <base href>
tag, which is located within an Ionic application’s src/index.html
file, appears like so:
<base href="/" />
This innocuous-looking tag is used to specify the base URL for the application from which all relative URLs are referenced, such as those used for internal navigation.
Put simply, the <base href>
value is the root location from which the Angular Router maps internal navigation URLs.
Router imports
The Angular Router is made available through the @angular/router
library package, which allows developers to access the available router modules such as:
- The
Router
module - The
RouterModule
module - The
RouteReuseStrategy
module - The
Routes
module - The
CanActivate
module - The
Resolve
module - The
ActivatedRouteSnapshot
module
Modules can then be imported from the Angular Router package, like so:
import { RouterModule, RouteReuseStrategy, Routes } from '@angular/router'
App Routing Module
We covered the App Routing Module in the previous lesson which, as previously explained, declares and contains the routing logic for the application, predominantly within the routes
array:
Get hands-on with 1200+ tech skills courses.