Angular Basics: Router Links and Wildcard Routing in Angular

Let’s take another look at routing in Angular—this time how you can use the router link to set up wildcards, so nonexistent URLs bring up a 404 page or redirect users to another page.


This content originally appeared on Telerik Blogs and was authored by Nwose Lotanna Victor

Let’s take another look at routing in Angular—this time how you can use the router link to set up wildcards, so nonexistent URLs bring up a 404 page or redirect users to another page.

In this post, we will look into more things you can do with the Angular Router’s router link in your template. This follows on work we did in the previous article.

Before We Start

This post is suited for all levels of frontend developers who use Angular, so being conversant with beginner concepts and installation processes is not assumed. Here are a few prerequisites you should have to be able to follow through this article’s demonstration:

  • An integrated development environment like VS Code
  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (it usually ships with Node installation)
  • Angular CLI version 8.0 or above
  • A recent version of Angular (this post uses version 12)

Other nice-to-haves include:

  • Working knowledge of the Angular framework at a beginner level

What Is Routing?

In the last article, we looked at how Angular makes it easy to bring in the navigation to your application through the router module. We also saw how routing can be set up in Angular with ease. Now that we have set up routing, there are a few more things we can do with the routing module.

What We Are Building

Today we are building a simple navbar component with navigation in a single-page application (SPA) and a wildcard page to guide users every time they enter a wrong URL. We are going to continue from the last post, so download the source file from here into your machine.

Setting Up

Open the new file in VS Code and inside the terminal run the command below:

npm install

This ensures all the node modules and dependencies needed for the project are properly installed. Your folder should have an app component with two child components: about and contact. The app component.html file should look like this:

<div class="container">
<ul class="nav justify-content-center">
  <li class="nav-item">
    <a class="nav-link active" aria-current="page" href="/">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="/about">About</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="/contact">Contact</a>
  </li>
</ul>
<router-outlet></router-outlet>
</div>

You can save your work and run the dev server to see that it all works well in the browser at localhost:4200.

ng serve

Single-Page Applications (SPAs)

A single-page web application is one that does not have to reload as you interact with it and navigate from one view to another—rather it dynamically displays views as requested. The first thing you notice with the application we have now is that every new click reloads the entire application, so it is not an SPA.

localhost:4200 adds a /about or /contact when we click on those names in the navigation, and a message shows  ‘about works!’ or  ‘contact works!’ respectively. Clicking  ‘Home’ removes the extra address word and the message.

Router links are element properties provided by the router module that makes a link initiate navigation. You can liken it to href for anchor tags, so in our case, we replace the href tags with router links.

<div class="container">
<ul class="nav justify-content-center">
  <li class="nav-item">
    <a class="nav-link active" aria-current="page" href="/">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" routerLink="/about">About</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" routerLink="/contact">Contact</a>
  </li>
</ul>
<router-outlet></router-outlet>
</div>

localhost:4200 adds a /about or /contact when we click on those names in the navigation, and a message shows  ‘about works!’ or  ‘contact works!’ respectively.

Wildcards

Now that we have set up routes, what happens if a user types in the wrong URL? A good application should always gracefully handle scenarios like this, where a user enters a URL that does not exist. Angular helps you do this with ease. You can set up a wildcard route to that effect.

Once you set up a wildcard route, it just tells the router to select this route anytime a requested URL does not match the specified routes in the app module. The syntax for defining a wildcard route looks like this:

{ path:**, component: WildcardComponent}

Let us see it in action with our application. Generate a new component, and call it Page404.

ng generate component page404

Now that you have created your wild card component, let us make it really clear. Open the page404 component.html file and change the paragraph content inside the html file from “page404 works” to “This URL you just entered is incorrect, kindly try again.”

<p>This URL you just entered is incorrect, kindly try again.</p>

Open the app module file and copy the code block below inside it:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { Page404Component } from './page404/page404.component';
const routes: Routes = [
  {path:'about', component: AboutComponent},
  {path:'contact', component: ContactComponent},
  {path:'**', component: Page404Component}
];
@NgModule({
  declarations: [
    AppComponent,
    AboutComponent,
    ContactComponent,
    Page404Component
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now if you try putting in any wrong URL, this is what you get:

adding random characters to the end of the URL brings up the error message, with  ‘This URL you just entered is incorrect, kindly try again.’

Redirecting the Routes

Besides creating a separate wildcard component like we have done, you can just redirect the route to go to another route like the Homepage or the Contact page whenever a user enters an incorrect URL.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { Page404Component } from './page404/page404.component';
const routes: Routes = [
  {path:'about', component: AboutComponent},
  {path:'contact', component: ContactComponent},
  { path: '**',   redirectTo: '/contact'}
];
@NgModule({
  declarations: [
    AppComponent,
    AboutComponent,
    ContactComponent,
    Page404Component
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now when you save the files, you will see that every incorrect URL redirects to the Contact page.

Conclusion

In this post, we have taken a further look at few routing elements that make the navigation experience even better for our users. We saw the router link and how it is used, and we also saw how to create wildcard routes to gracefully handle users entering incorrect URLs.


This content originally appeared on Telerik Blogs and was authored by Nwose Lotanna Victor


Print Share Comment Cite Upload Translate Updates
APA

Nwose Lotanna Victor | Sciencx (2022-02-01T09:52:03+00:00) Angular Basics: Router Links and Wildcard Routing in Angular. Retrieved from https://www.scien.cx/2022/02/01/angular-basics-router-links-and-wildcard-routing-in-angular/

MLA
" » Angular Basics: Router Links and Wildcard Routing in Angular." Nwose Lotanna Victor | Sciencx - Tuesday February 1, 2022, https://www.scien.cx/2022/02/01/angular-basics-router-links-and-wildcard-routing-in-angular/
HARVARD
Nwose Lotanna Victor | Sciencx Tuesday February 1, 2022 » Angular Basics: Router Links and Wildcard Routing in Angular., viewed ,<https://www.scien.cx/2022/02/01/angular-basics-router-links-and-wildcard-routing-in-angular/>
VANCOUVER
Nwose Lotanna Victor | Sciencx - » Angular Basics: Router Links and Wildcard Routing in Angular. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/01/angular-basics-router-links-and-wildcard-routing-in-angular/
CHICAGO
" » Angular Basics: Router Links and Wildcard Routing in Angular." Nwose Lotanna Victor | Sciencx - Accessed . https://www.scien.cx/2022/02/01/angular-basics-router-links-and-wildcard-routing-in-angular/
IEEE
" » Angular Basics: Router Links and Wildcard Routing in Angular." Nwose Lotanna Victor | Sciencx [Online]. Available: https://www.scien.cx/2022/02/01/angular-basics-router-links-and-wildcard-routing-in-angular/. [Accessed: ]
rf:citation
» Angular Basics: Router Links and Wildcard Routing in Angular | Nwose Lotanna Victor | Sciencx | https://www.scien.cx/2022/02/01/angular-basics-router-links-and-wildcard-routing-in-angular/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.