16
NovRouting in Angular - Types of Routing in Angular With Example
Angular Routing
Routing in Angular is one of the most exciting features that make it so useful for developing dynamic web applications. Routing is what allows you to navigate between different pages or views in your application without having to reload the entire page. Consider it a traffic controller, sending users to different sections of your app based on the URL they visit. It's what creates the smooth single-page experience. If you've already worked with URLs and links, Angular will feel like magic.
So, In this Angular Tutorial, we will look briefly at what is Angular Routing. Let's go into how it works!
What is Angular Routing?
Routing is a way to serve web pages based on the requested URL. In Angular which is used to build SPA, URLs are not served from the server and never reload the page. The URLs are strictly local in the browser and serve the page(components) from local. Every time you request a URL, the Angular router navigates to the new component renders its template, and updates the history and URL.Purpose of Routing in Angular
The angular router can interpret a browser URL as an instruction to navigate from/to the specific view. One can pass the optional parameters along with the supporting view component that helps it decide what specific content to present. We can bind the router to the links on a page, and it will navigate to the defined application view when the user clicks a link. Understanding the functionalities and intricacies of the Angular router is a vital aspect covered in Angular certification Training.
Steps to Configure Angular Routing
The Angular router has its library package which is @angular/router
So we need to import what we need from it as we would from any other Angular package. It is an optional service in angular that presents a particular component view.
There are following steps you have to follow to configure routing in Angular.
Step1: Define the routes
Angular application routes are recommended to be defined within a separate module using an array as given below:
import { NgModule } from '@angular/core';
const routes: Routes = [
{ path: "", component: HomeComponent },
{ path: "about", component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
Step 2: Define the container
RouterOutlet
as the container where the router renders the component when the user requests a route.
<div>
<router-outlet></router-outlet>
</div>
Step 3: Define the links
RouterLink
directive, which is used to define links to a route name.
<ul class="nav navbar-nav">
<li>
<a [routerLink]="['/']">Home</a>
</li>
<li>
<a [routerLink]="['/about']">About</a>
</li>
</ul>
Step4: Define Route for 404
In Angular, you can define a route that will be served, if the requested URL doesn't match any paths in the route configuration. The ** characters are used to define the path for the route not found. You can define this path as given below:
const routes: Routes = [
{ path: "", component: HomeComponent },
{ path: "about", component: AboutComponent },
{ path: "notfound", component: NotfoundComponent },
{ path: "**", redirectTo: "notfound" }
];
Note
In Angular routes configuration, the order of the routes matters. The angular router uses a first-match wins strategy when matching routes.
So more specific routes should be placed at the top level and less specific routes should be placed at the bottom in the routes configuration.
Common Routing Tasks
1. Generate an Application
The first step when working with Angular routing is to create a new Angular application using the Angular CLI.
ng new my-app
This command creates a new Angular project called my-app
. You’ll be prompted to enable Angular routing during the setup. Type Y to enable it.
Once the application is generated, you will have a basic folder structure along with a app-routing.module.ts
file, where you can define your routes.
2. Defining a Basic Route
To define routes for navigating between views, use the RouterModule
in app-routing.module.ts
:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', component: HomeComponent }, // Default route
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
3. Getting Route Information
You can retrieve information about the current route such as route parameters or query parameters by injecting ActivatedRoute
into your component.
import { ActivatedRoute } from '@angular/router';
export class UserComponent {
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Get route parameter (e.g., /user/:id)
this.route.params.subscribe(params => {
console.log('User ID:', params['id']);
});
// Get query parameters (e.g., /user?id=123)
this.route.queryParams.subscribe(params => {
console.log('Query params:', params);
});
}
}
4. Setting up Wildcard Routes
Wildcard routes are used to catch any undefined routes in your application and display a 404 page.
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '**', component: PageNotFoundComponent } // Wildcard route
];
5. Displaying a 404 Page
Create a 404 error page using a component that shows an error message when a user navigates to an undefined route.
// page-not-found.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-page-not-found',
template: `404 Page Not Found`,
styles: [`h1 { color: red; }`]
})
export class PageNotFoundComponent {}
6. Setting up Redirects
Sometimes, you want to redirect a user from one route to another. Use the redirectTo
property in your route configuration to do this:
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' }, // Redirect empty path to /home
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '**', component: PageNotFoundComponent } // Wildcard route
];
What is Location Strategies?
Location Strategies in Angular defines how the URL/Request is being resolved and determines how your URL will look in the browser. Angular supports two types of Location Strategies. There are two types of location strategies
- PathLocation Strategy
- HashLocation Strategy
1. PathLocation Strategy
The PathLocation strategy is the default location strategy in Angular. In this strategy, the URL looks like the multi-page application as http://localhost:4200/product
. This strategy can be configured as given below:
//step1: src/index.html
<base href="/"> Use at main page i.e. index.html page
//step2: src/app/app.routing.ts
RouterModule.forRoot(appRoutes) in routing module
Advantages and Disadvantages of PathLocation Strategy
- Supports Server-Side Rendering
- SEO Friendly
- Older browsers don’t support
2. HashLocation Strategy
The hashLocation strategy you have to configure in Angular. In this strategy, the URL contains a hash character as http://localhost:4200/#/product
. This strategy can be configured as given below:
//step1: src/index.html
<base href="/"> Use at main page i.e. index.html page
//step2: src/app/app.routing.ts
RouterModule.forRoot(appRoutes, {useHash: true}) in routing module
Advantages and Disadvantages of HashLocation Strategy
- Supported by all browsers
- Doesn't Support Server-Side Rendering
- Not SEO Friendly because of special character Hash
Child/Nested Routes
Sometimes you need to render one or more components on request on a component. In that case, child/nested routing helps us. This is a powerful feature in Angular router to render child/nested components in Angular using the route.
Configuring Child/Nested Routes
To define a child/nested route a Children option is used in the routes array as given below:
const routes: Routes = [
{ path: "", component: HomeComponent },
{ path: "about", component: AboutComponent,
children: [
{ path: "profile", component: ProfileComponent },
{ path: "changepassword", component: ChangepasswordComponent }
]
}
];
<h2>About Us</h2>
<hr>
<p>This is about us page for the company!</p>
Activating the Child Routes
<a [routerLink]="['profile']">Profile</a>
<a [routerLink]="['changepassword']">Change Password</a>
<router-outlet></router-outlet>
Read More:
Summary
This article is meant to get started with the concept of routing in Angular. It's meant to show the most common uses, not all of them.For any application, navigation is one of the important features that one can ask for. Even though a single-page application (SPA) does not have a multiple-page concept, it does move from one view to another view. Providing clear and understandable navigation elements decides the success of an application pretty loudly. Enroll in Angular Training to gain a deeper understanding of Angular routing and related concepts.FAQs
- Enhanced User Experience: Navigate between views with ease, just like in desktop apps, without having to reload the entire page.
- Faster Page Transitions: Load only the necessary components, resulting in faster transitions and improved performance.
- Modularity and Maintainability: Organise code effectively by associating components with specific routes, hence increasing reusability.
- SEO-Friendly URLs: Improve discoverability by using URLs that represent view content, which helps with search engine optimization.
- Advanced Navigation: Handle complex scenarios with support for route parameters, child routes, and route guards to improve security.
Take our Angular skill challenge to evaluate yourself!
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.