Angular - Routing in Single-Page Applications



This tutorial (chapter) describes, how to build a single-page application (SPA). A angular application that uses the multiple routes to make it SPA.

What is Single-Page Application?

A single-page Application (SPA) is a web application or website that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from the server. The routing features in Angular allow developers to develop and design a single-page application.

Create a Sample Application

Let's create a sample Angular application with two different components to demonstrate how to achieve a single-page application (SPA) by setting up routing.

We will use the Angular CLI to create a new sample angular application. Use the following steps to create a new application:

Step 1: Open the node.js command or IDE's terminal (such as VS code) and go to your favorite workspace as follows:

cd /go/to/your/favorite/workspace

Step 2: Install the Angular CLI using the following command (see more):

install @angular/cli

or for latest version
install @angular/cli@latest

Step 3: Create a new angular application as follows(see more):

ng new mySPA

Enable the stylesheet by choosing the following option:

? Which stylesheet format would you like to use? (Use arrow keys)
->CSS
  SCSS   [ https://sass-lang.com/documentation/syntax#scss                ]
  Sass   [ https://sass-lang.com/documentation/syntax#the-indented-syntax ]
  Less   [ http://lesscss.org                                             ]

When prompted with Do you want to enable Server-Side Rendering, select No.

Now go to your newly created application using the cd mySPA command.

Step 4: Create a component with the name Home as follows:

ng generate component Home

In your IDE (code editor), locate the file,home.component.html, and replace the placeholder content with the following HTML code:

<h3>Welcome to Home</h3>
<p>All content will be visible here...</p>

Step 5: Create a component with the name Contact as follows:

ng generate component Contact

In your IDE (code editor), locate the file,contact.component.html, and replace the placeholder content with the following HTML code:

<h3>Welcome to Contact</h3>
<p>You can contact us here..</p>

Step 6: Now, in your code editor open the app.component.html file and replace its code with as follows:

<h1>Angular Router Sample Application</h1>
...
<app-home></app-crisis-list>
<app-contact></app-heroes-list>

Step 7: Verify that your newly created application runs as expected by running thefollowing command:

ng serve

Step 8: Open the browser and navigate to localhost:4200.

You should see a single web page, consisting of a title and the HTML of your two components.

Define Routes

In this section, we will define two routes as follows:

  • The router /home will open the HomeComponent.
  • The router /contact will open the ContactComponent.

In Angular, a route defines the path for different sections (components). Each route has two properties. The first property,path, is a string that specifies the URL path for the route. The second property,component, is a string that specifies what component your application should display for that path.

Step 1: In your IDE, open the app.routes.ts file (create it manually, if does not exist) as follows:

import { Routes } from '@angular/router';

export const routes: Routes = [];

Step 2: Add routes for the two-component you have created:

import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ContactComponent } from './contact/contact.component';

export const routes: Routes = [
    {path: 'home', component: HomeComponent},
    {path: 'contact', component: ContactComponent}
];

This routes list is an array of objects (i.e., JavaScript objects), with each object defining the properties (path and component) of a route.

Import provideRouter

To add this functionality to your sample application, you need to update theapp.config.tsfile to use the router providers function,and import provideRouter as follows:

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes)]
};

Note: For@NgModule-based applications (i.e., older version), put theprovideRouterin theprovider'slist of theAppModule (i.e., app.module.ts) or wherever the module is passed tobootstrapModulein the application.

Update the Component with router-outlet

To ensure that your defined routes work and dynamically load components based on the URL, you need to update your app.component.html file with the router-outlet directive. This directive acts as a placeholder for the routed components to be displayed.

Step 1: In your code editor, open the app.component.html file and delete the following

<h1>Angular Router Sample Application</h1>
...
<app-home></app-crisis-list>
<app-contact></app-heroes-list>

Step 2: Add the router-outlet directive to your app.component.html file:

<router-outlet></router-outlet>

Step 3: Import the RouterOutlet in your app.component.ts file as follows:

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ContactComponent } from './contact/contact.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, HomeComponent, ContactComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'mySPA';
}

Look at your updated application in your browser. To view the Home component, add /home to the end of the http://localhost:4200 URL:

http://localhost:4200/home

You can notice that thehomecomponent is displayed. Angular is using the route you defined to dynamically load the component. You can load theContactcomponent in the same way:

http://localhost:4200/contact

Controlling Navigation with Template

The application we have developed supports two routes. However, the only way for the user to navigate between different components is by manually changing the URL.

In this tutorial section, we will learn how to navigate through the different components without changing the URL manually.

We will create two links that users can click to navigate between the Home and Contact components. We will add some CSS to these links that will give more clarity about the currently loaded page.

Step 1: Open the app.component.html file and add the below code:

<nav>
    <a routerLink="/home" class="my-link">Home</a>
    <a routerLink="/contact" class="my-link">Contact</a>
</nav>
<div class="load">
    <router-outlet></router-outlet>
</div>

Step 2: Open the app.component.css file and add the code below:

nav{
    padding: 20px 0px;
    border-bottom: 1px solid black;
}
nav .my-link{
    margin: 10px 10px;
    position: relative;
    top: 5px;
    text-decoration: none;
    background-color: rgb(39, 110, 55);
    color: white;
    padding: 10px 30px;
    border-radius: 10px;
    border: 1px solid black;
    box-shadow: 0px 5px 15px rgba(0, 0, 0, 0.35);
}
.load{
    margin: 30px 0px;
}

If you view your application in the browser, you should see these two links. When you click on a link, the corresponding component will load dynamically:

Adding a Redirect

In this section of the tutorial, we will add a route that redirects you to the /home component directly when you navigate to http://localhost:4200.

Step 1: In your code editor open the app.route.ts file.

Step 2: Update the existing code with the following:

import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ContactComponent } from './contact/contact.component';

export const routes: Routes = [
    {path: '', redirectTo: 'home', pathMatch: 'full'},
    {path: 'home', component: HomeComponent},
    {path: 'contact', component: ContactComponent}
];

As you can see, we have added new routes with an empty path (''). In addition, it replaces the component property with two new properties as follows:

  • redirectTo: This property instructs Angular to redirect from an empty ('') path to the 'home' path.
  • pathMatch: This property instructs Angular on how much of the URL to match. If you keep it as a "full",it will match the entire path.

Note: Now, when you open your application (navigate on browser localhost:4200), it displays the Home component by default as follows:

Adding 404 page

A user can try to access a route that you have not defined. To acknowledge this behavior, the best practice is to display a 404 page. In this section, we'll create a 404 page (component) and update our route configuration to show that page for any unspecified routes.

Step 1: From your code editor terminal, create a new component with the name pageNotFound as follows:

ng generate ccomponent pageNotFound

Step 2: In your code editor, open the page-not-found.component.html file and replace its contents with the following HTML code:

<h2>Page Not Found</h2>
<p>The page you looking for, we could not found....!!!</p>

Step 3: Open the app.routes.ts file and add the following route to the routes list at the end (if not other routes will not work properly):

{path: '**', component: PageNotFoundComponent}

The new route uses a path as "**". This path is how Angular identifies a wildcard route. Any route that does not match an existing route in your configuration will use this route in the application.

Make sure that the wildcard route (**) is placed at the end of the array. The order of your routes is important, as Angular applies routes in order and uses the first match it finds; otherwise, the routes will not work properly.

Now, try to navigate the non-existing route, for example, localhost:4200/about, it will redirect you to the page-not-found component, as the "/about" route does not match with any defined routes in your app.routes.ts file.

Multiple Choice Questions (MCQ's):

Here we have mentioned a few MCQs to test your knowledge on the current concept:

Answer : A

Explanation:

A Single-Page Application (SPA) in Angular loads a single HTML page and dynamically updates the content as the user interacts with the application.

Q 2 − Which method is commonly used to define routes in an Angular SPA?

A − HttpClient.get()

B − RouterModule.forRoot()

C − FormsModule.configure()

D − CommonModule.setup()

Answer : B

Explanation:

The RouterModule.forRoot() method is used to define routes in an Angular SPA.

Answer : C

Explanation:

The RouterLink directive is used to define navigation paths within the application.

Advertisements