Routing allows your application to change views and navigate between different components without reloading the entire page. It improves the user experience by providing seamless transitions between views.
Angular applications are mostly single-page applications (SPAs), meaning they load a single HTML page and dynamically update it as the user interacts with the application.
In your journey as a web developer, you may have seen many websites with links that allow you to navigate to a new page without reloading the page. This can be achieved through routing.
With routes, you can lazy load specific components, meaning you can load only the necessary sections of the code when required, improving performance and reducing initial load time.
For more details, check out the new official documentation.
Here is the step-by-step guide to implementing basic routing in Angular:
Step 1: Setup an Angular Project
Angular 18 comes with routing by default. You don’t need to configure it manually, as it does this by default.
To set up a new project, you must first install the AngularCLI and create a new project.
If you have not installed AngularCLI, then you can install it using the below command:
npm install -g @angular/cli
Now, you can create a new Angular project using the below command:
ng new routing-app
Now go inside the project folder “routing-app” and open the folder in your favorite code editor:
If you navigate to the src/app folder, you will see a file called app.routes.ts file like this:
import { Routes } from '@angular/router'; export const routes: Routes = [];
This file comes by default with a new project with the above code.
The app.routes.ts file is registered in the Angular application, and if you want to see that, open the src/app/app.config.ts file:
import { ApplicationConfig, provideExperimentalZonelessChangeDetection } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; export const appConfig: ApplicationConfig = { providers: [ provideExperimentalZonelessChangeDetection(), provideRouter(routes), provideAnimationsAsync(), ], };
This is an Angular configuration file. We passed the routes in this file using the provideRouter() function.
Now, this configuration file src/app/app.config.ts is used in the src/app/main.ts file:
import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from './app/app.config'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err) );
This bootstrap application file loads when the Angular project boots up.
Step 2: Install Angular Material
This step is optional, and you don’t need to install it, but for this project, I want some styling, so I am installing it using the below command:
ng add @angular/material
Import the two necessary material modules in the src/app/app.component.ts file that will help us style our project:
import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatButtonModule } from '@angular/material/button'; @Component({ selector: 'app-root', standalone: true, imports: [MatToolbarModule, MatButtonModule, RouterOutlet], templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent {}
Step 3: Adding components for routing
Our application needs at least two components to navigate between them and at least one of each component to use the Angular router.
To create a component using the CLI, enter the following at the command line:
ng generate component home
It will create a home folder inside the src/app directory, and in the home directory, you will have these files:
- home.component.css
- home.component.html
- home.component.spec.ts
- home.component.ts
Now, create another component called about using the below command:
ng generate component about
It will create an about folder with the above files, except the name will be “about.”
Step 4: Importing new components
After creating two new components, we must import them inside the src/app/app.routes.ts file for routing.
// app.routes.ts import { Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; export const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, ];
Here, we declare the Routes array.
Each route in this array is a JavaScript object that contains two properties.
The first property, path, defines the URL path for the route.
The second property, component, defines the component Angular should use for the corresponding path.
The third property is optional, called “redirectTo”, which tells us which route you want to redirect. The fourth is “pathMatch.”
Step 5: Adding routes to our application
First, we defined the routes for our routing application. Now, we need to use them for our application.
First, add links to the two components.
Assign the anchor tag that you want to add the route to the routerLink attribute.
Set the value of the attribute to the component to show when a user clicks on each link.
Next, update the app.component.html template to include <router-outlet>. This element informs Angular to update the application view with the component for the selected route.
Write the following code inside the src/app/app.component.html file:
<mat-toolbar color="primary"> <span>My Application</span> <span class="spacer"></span> <a mat-button routerLink="/home">Home</a> <a mat-button routerLink="/about">About</a> </mat-toolbar> <router-outlet></router-outlet>
Also, import the RouterLink and RouterLinkActive modules into the src/app.component.ts file:
import { Component } from '@angular/core'; import { RouterOutlet, RouterLink, RouterLinkActive } from '@angular/router'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatButtonModule } from '@angular/material/button'; @Component({ selector: 'app-root', standalone: true, imports: [ MatToolbarModule, MatButtonModule, RouterOutlet, RouterLink, RouterLinkActive, ], templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent {}
Step 6: Run the routing application
Go to the terminal and start the development server using this command:
ng serve --open
If you click on the About link, it will display about component like this:
That’s all!
vishnu
thank you
dgrfg
with parameters?
manouchehr
thanks lot
Great Efue
Thanks
Hemant
You are awsome Bro.
GregJF
You don’t show how the student,module is routed to from the rest of the app