This article demonstrates routing concepts in angular. We will understand below points as part of the routing concepts:
- Introduction of Routing
- Steps to implement Routing
- Refactoring Routing Configuration into a routing module
- Parameterized Routes And Extracting Parameters Using ActivatedRoute
- Redirecting from one component to another with query params
- Nesting of routes / Child Routes
- Route Guards
Prerequisite
Basic understanding of components, and modules in angular.
Introduction of Routing
Angular serves webpages based on the requested URL. Based on the requested URL, angular navigates to the respective component & renders.
- Angular provides ‘@angular/router’ library to enable routing in our application.
- Routing is used to navigate from one view to another when the user performs any task.
- Angular router provides us to pass optional parameters along to the corresponding component to display the specific content.
- RouterLink, RouterLinkActive, and RouterOutlet are directives provided by the Angular RouterModule package. They are readily available to use in the template.
Steps to implement Routing
Step 1 - Import a module "RouterModule"
We need to import the router module in app.module.ts which is part of @angular/router
import { RouterModule } from '@angular/router';
Step 2 - Define routes
Create a route table with URL path and component which will load while navigating to this path. For example -
const routes: Routes = [{
path: 'pipe',
component: PipeSampleComponent
}, {
path: 'datasharing',
component: CustomerAddComponent
}];
We can also add a catch all route by using the path **, if the URL doesn’t match any of the other routes it will match this route.
Step 3 - Map the routes with RouterModule
Import router module in app module.
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(routes)
],
There are two ways to register routes:
- RouterModule.forRoot creates a module that contains all the directives, the given routes, and the router service itself.
- RouterModule.forChild creates a module that contains all the directives and the given routes but does not include the router service.
Step 4 - Add a placeholder for rendering the component
Add placeholder router-outlet in app.component.html. This directive displays the inner content of the corresponding route component template in the current view.
<router-outlet></router-outlet>
Step 5 - Provide a link to click using routerLink for Navigation
The routerLink attribute is mostly used either on <a> or <button> tags which gives the router control over the element.
<a class="nav-link" [routerLink]="['pipe']">Pipe</a>
routerLinkActive attributes will select the route as default route. For example -
<button class="btn btn-primary" routerLink="/path" routerLinkActive="red">first route</button>
Refactoring Routing Configuration into a routing module
In enterprise applications, routing sections keep on growing over the period of time and it’s recommended to create a separate routing module for this. Here is a sample example of implementation:
Step 1 - Create new routing module
Let’s create a new module for routing using cli command “ng g m AppRouting”
![Understanding Routing In Angular]()
Step 2 - Define, Map routes, and export Router Module
Inside AppRouting module, we need to perform 3 things:
- Define routes which is referred as route table
- Import router module
- Export router module
![Understanding Routing In Angular]()
Step 3 - Import AppRouting module into app.module
Now you need to include AppRoutingMoudle in AppModule imports array.
![Understanding Routing In Angular]()
Parameterized Routes And Extracting Parameters Using ActivatedRoute
To read/accept the route value in the target component, we need to import ActivatedRoute class and inject it into our component. ActivatedRoute is a class that is used to read the information from activated URLs.
The parameters are wrapped in an Observable that will push the current route parameter value whenever the parameter is updated. We subscribe for any changes. When a new value is received, we set the value to a property on our template.
Let’s see some of the example implementations.
Example 1 - Reading a route value
Firstly, we need to register the path and component into the route table. Here, the id value has been passed in URL and reading into component.
{path: 'route/:id', component: RoutingSampleComponent},
This is what we can navigation to the component.
<a class="nav-link" routerLinkActive='red' [routerLink]="['route', '']">Routing</a>
Secondly, in component we need to read the params value using ActivatedRoute class which is injected in constructor.
![Understanding Routing In Angular]()
Here we can see that route value in the component can easily be accessed (can be displayed in UI, if required).
![Understanding Routing In Angular]()
Example 2 - Reading a querystring value
To pass the query string value, we need to use [queryParams] as in the below example.
<a class="nav-link" routerLinkActive="active" [routerLink]="['route', '0']" [queryParams]="{city:'bangalore', country:'india'}">Routing</a>
Inside the component, we need to read the queryParams value using ActivatedRoute class which is injected in the constructor.
this.activatedRoute.queryParams.subscribe((data) => {
this.City = data['city'];
this.Country = data['country'];
});
Here we can see that query Params value in the component can easily be accessed (can be displayed in UI, if required).
![Understanding Routing In Angular]()
Redirecting from one component to another with query params
To redirect one component to another with some query params value, we need to perform two things:
- first, we need to inject a class called Router
- then, we need to use router.navigate methods for actual navigation on click events.
Here is a sample example:
![Understanding Routing In Angular]()
<input type="button" class="btn btn-secondary" value="Redirect to Route Page" (click)="redirect()" />
Nesting of routes / Child Routes
To view route within another route we use nested (or) child routes i.e., now we will have two <router-outlet> tags, where one route will be primary and other one will be a child of the primary.
Firstly, we need to add children to the route table.
![Understanding Routing In Angular]()
Then we need to add a placeholder in the component where you wish to implement nesting of routes <router-outlet></router-outlet>
Here we have child <router-outlet> in the parent component and router link to navigate to the child.
![Understanding Routing In Angular]()
Here we can see that the child component is loaded within a parent component using the child route.
![Understanding Routing In Angular]()
Note: Path which has redirectTo property cannot have children.
Route Gurds
Route guards in Angular are interfaces that determine if a route can be activated or deactivated. They are used to control access to certain parts of the application and ensure that the user has the necessary permissions before navigating to a particular route.
- Route guards are function that get triggered automatically based on route activation / deactivation
- Helps us to protect routes from unauthorized access
- Types of guards
- CanActivate - Triggered when route is activated
- CanDeActivate - Triggered when route is about to leave
- CanLoad - Can be applied only to lazy loading route. This will not allow the js chunk to get downloaded
- CanActivateChild - Apply guard on the parent route, but get applied on the children routes
- CanMatch - Combination of CanLoad & CanActivate
Source Code here.
Happy Learning!