A Complete Guide To Angular Routing
Last Updated : 23 Jul, 2024
Angular Routing is a technology to build single-page applications that provide multi-page services at a single port. It enables seamless navigation and loading of the different pages. When an Angular app is started then the whole component is only loaded at once and dynamically reloads the requested pages through routing technology.
Angular RoutingThis tutorial is going to give you a complete guide to How Angular Routing actually works and what are the features and their advantages. At the end of this tutorial you will be able to implement routing feature in your Angular Project and also you will have a clear idea about how angular routing makes an application very efficient by loading only those component instead of whole pages which has requested by an user.
Introduction to Angular Routing
The Angular router is a core part of the Angular application and is responsible for mapping URLs to components and rendering different components based on the current URL matches in an Angular application.
- We should have clear idea about this Routing feature, it is responsible for page rendering not for navigating links. Many times developers have misconception that when we click navigation bar then page will change but the scenario is different whenever we interact with any navigation elements then it only set the URL or we can say change the URL.
- After changing the URL, the responsible Angular Routing Module notes down the new URL and then renders components accordingly.
Prerequisites
Steps to Create an Angular Application
Step 1: After the global setup of Node Js and npm Packages now we have to install Angular globally by using the below mentioned command
npm install -g @angular/cli
Step 2: Run the command below to create a new Angular Application.
ng new project_name
Step 3: Change the directory using below command to enter in our Project environment.
cd project_Name
Step 4: Run the command below to create components.
ng generate component Home
ng generate component About
ng generate component Contact
Step 5: Run the below command to start the server.
ng serve
Dependencies
"dependencies": {
"@angular/animations": "^18.1.0",
"@angular/common": "^18.1.0",
"@angular/compiler": "^18.1.0",
"@angular/core": "^18.1.0",
"@angular/forms": "^18.1.0",
"@angular/platform-browser": "^18.1.0",
"@angular/platform-browser-dynamic": "^18.1.0",
"@angular/platform-server": "^18.1.0",
"@angular/router": "^18.1.0",
"@angular/ssr": "^18.1.0",
"express": "^4.18.2",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Folder Structure
Folder Structure HTML <!-- app.component.html --> <h1>Angular Router App</h1> <nav> <ul> <li><a routerLink="/" routerLinkActive="active" ariaCurrentWhenActive="page"> Home</a></li> <li><a routerLink="/about" routerLinkActive="active" ariaCurrentWhenActive="page"> About</a></li> <li><a routerLink="/contact" routerLinkActive="active" ariaCurrentWhenActive="page"> Contact</a></li> </ul> </nav> <router-outlet></router-outlet>
HTML <!-- home.component.html --> <p>Home Component</p>
HTML <!-- about.component.html --> <p>About Component</p>
HTML <!-- contact.component.html --> <p>Contact Component</p>
JavaScript // app.routes.ts import { Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; import { ContactComponent } from './contact/contact.component'; export const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'contact', component: ContactComponent } ];
JavaScript //app.component.ts import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { RouterLink, RouterLinkActive } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet, RouterLink, RouterLinkActive], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { title = 'route'; }
Example :- Step to run the application: Open the terminal and type the following command -
- The file app.component.html includes the main page where rendering process start and ends .
- The file app.routes.ts is basically for enlisting all the Route related components.
- The file home.component.html simply includes home component elements.
- The file about.component.html simply includes About component elements.
- The file contact.component.html simply includes Contact component elements.
ng serve
Output :
We can see :
- Home component at : http://localhost:4200/
- About component at : http://localhost:4200/about
- Contact Component at : http://localhost:4200/contact
Some Important Angular routing concepts
1. Child Routes
Child routes in Angular are used to create nested routes within a parent route. This is useful for organizing routes that share a common path or component structure. You might have a main component with several sub-components, each accessible via its own route. It can be implemented like -
const routes: Routes = [
{
path: 'parent',
component: ParentComponent,
children: [
{
path: 'child1',
component: Child1Component
},
{
path: 'child2',
component: Child2Component
}
]
}
];
2. Lazy Loading
Lazy loading is a technique used to load feature modules on demand rather than upfront. This improves the performance of your application by loading only the necessary parts initially and loading additional parts as needed.
To implement lazy loading, you define a route with the 'loadChildren' property instead of 'component'. This property points to a function that returns the module to be loaded.
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];
3. Route Guards
Route guards are used to control access to certain routes based on conditions such as authentication status, user roles, or other criteria.
Angular provides several types of route guards -
- CanActivate: Determines if a route can be activated.
- CanDeactivate: Determines if a route can be exited.
- CanActivateChild: Determines if child routes can be activated.
- CanLoad: Determines if a module can be loaded.
Here is the some Functions and Module explanation which are used in above code snippet :-
- RouterOutlet : Directive to specify where the router should render the active component.
- RouterLink : Directive to create links to other routes.
- RouterLinkActive : Directive to highlight the active link in your navigation bar.
- ActivatedRoute : Service to access information about the current route, such as the route parameters.
- NavigationExtras : Object to pass additional data to the router when navigating to a new route.
Finally, we well-versed through Angular Routing and now you are able to implement Routing in your Angular Project.
Similar Reads
How to create module with Routing in Angular 9 ?
Angular applications are modular, and NgModules is Angular's own modular architecture. NgModules are containers for closely integrated application domains, workflows, or feature sets that comprise cohesive code blocks. Their scope is governed by the NgModule they include, and they can contain compon
4 min read
Introduction to Angular Concepts
Angular, a powerful front-end framework developed by Google, has revolutionized the way modern web applications are built. For newcomers to web development, Angular can seem to be a great choice due to its features, concepts, and terminologies. In this article, we'll see more about the journey of An
5 min read
How to create a new component in Angular?
A component in Angular is the building block for making web pages. It is a reusable block of code that can be used anywhere in the app any number of times. It provides scalability, reusability, and readability. Each component does a specific job like showing a menu, a photo or a card, etc. In this a
3 min read
Introduction To Components And Templates in Angular
Angular is a powerful framework for building dynamic, single-page web applications. One of the core concepts that make Angular so effective is its use of components and templates. Components and templates are the building blocks of any Angular application, allowing developers to create reusable, mai
6 min read
How to Create a new module in Angular ?
Modules are most important when it comes to building strong and scalable Angular applications. They help organize your code, promote modularity, and improve maintainability. It encourages collaboration among developers by grouping related components, directives, pipes, and services. In this article,
3 min read
How to setup 404 page in angular routing ?
To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple angular component called PagenotfoundComponent. Creating Component: Run the below command to create pagenotfound component. n
2 min read
How to bundle an Angular app for production?
Introduction Before deploying the web app, Angular provides a way to check the behavior of the web application with the help of a few CLI commands. Usually, the ng serves command is used to build, watch, and serve the application from local memory. But for deployment, the behavior of the application
4 min read
How to detect a route change in AngularJS ?
In this article, we will see how to detect a route change in AngularJS. In order to detect route change at any moment in AngularJS, this can be achieved by using the $on() method. The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/vi
2 min read
AngularJS Questions Complete Reference
AngularJS is a JavaScript open-source front-end framework that is mainly used to develop single-page web applications(SPAs). It is a continuously growing and expanding framework which provides better ways for developing web applications. This is the most used framework in India compare to other fron
8 min read
Routing in Angular 9/10
Routing in Angular allows the users to create a single-page application with multiple views and allows navigation between them. Users can switch between these views without losing the application state and properties. Approach: Create an Angular app that to be used.Create the navigation links inside
3 min read