Angular Basics: Using the Router in Angular 12 to Navigate Views

Single-page apps (SPAs) allow multiple views on the same web page, and Angular Router helps you navigate those and decide what to do about the URL for each view.


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

Single-page apps (SPAs) allow multiple views on the same web page, and Angular Router helps you navigate those and decide what to do about the URL for each view.

Building single-page applications (SPAs) is fun, especially when you're getting started in Angular, and in this post you will learn one of the ways Angular has made it really easy to achieve this with minimal effort.

Prerequisites

To be able to follow through in this article’s demonstration you should have:

  • An integrated development environment (IDE) 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
  • The latest version of Angular (version 12):
ng version

Confirm that you are using version 12, and update to 12 if you are not.

Other things that will be nice-to-haves are:

  • Working knowledge of the Angular framework at a beginner level

One of the amazing things about building SPAs (single-page apps) is the ability to have multiple views in it. Using Angular makes this very easy because you can dynamically display multiple views in one component through navigation tools. You can go from a home page to an “About” page to a “Contact Us” page all in one component.

Why Routing Is Important

Imagine a scenario where you go from one view to another in your SPA but the URL does not change at all. Like you click on the “About Us” button and the page appears in the DOM but the URL still says “newapp.com” instead of “newapp.com/about”.

This immediately brings a few issues to mind. The first is: How can you bookmark the particular view, seeing that bookmarks save URLs and not app views? Other challenges include how the concept of refreshing a page would work since the URL is basically static and how you even share a link with other people.

Routing ensures that the URL matches the view that is displayed so that you can easily separate views, maintain state and even have intuitive web experiences.

What Is the Angular Router?

The Angular Router is a JavaScript router built and maintained by the Angular team. It has an extensive routing package that lets you define exactly what URL string you want to assign to a view. You can have multiple router outlets, path matching and even route guards. This is such an important part of Angular that ensures SPAs can be built easily using the framework.

What We Are Building

We are going to build a small music TV app that shows two views as you click on the buttons that connect them, as shown below:

The URL ends in  “/artists” when you click on the Artists button and  “/records” when you click on the Records button.

Setting up

To start off, open VS Code and in the terminal create a new angular app with the command below:

ng new newap --routing

Adding the routing flag automatically scaffolds a new Angular app called newapp with routing pre-configured out of the box.

Now change the directory. Navigate into the app root folder with this command:

cd newapp

The Two Components

The next thing to do is to generate the new components that would house the two views we plan to alternate between.

ng generate component artists -it -is
ng generate component records -it -is

These two commands create new folders inside the source’s app folder called Artists and Records with inline styles and templates, just like Vue.js by default. The next thing to do is to configure the routes to suit our needs.

Configuring the Routes

To configure the router, copy the code block below into your app-routing.module.ts file:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ArtistsComponent } from './artists/artists.component';
import { RecordsComponent } from './records/records.component';
const routes: Routes = [
  {path:'artists', component:ArtistsComponent},
  {path:'records', component:RecordsComponent}
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
export const ArrayOfComponents = [ArtistsComponent, RecordsComponent]

First, we imported the two components; then we configured the routes. Notice how we defined the URL string we wanted as Artists and Records and matched them to the two components. In order not to keep on importing the components everywhere else we might need, we created an array of components instead.

To register this new development, open your app module file and copy in the code block below:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule, ArrayOfComponents } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent,
    ArrayOfComponents
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here we registered the new array of components. As you can see, we did not need to import the two components inside the array any longer. This is a great way to keep your code maintained properly.

The next thing to do is to build the app template itself, to reflect all of the things we have done. The router link is a part of the Angular Router used to indicate links—it is critical inside the template when you want to point to a view. In the app component HTML file, replace the content with the code block below:

<div class="car">
<div style="text-align:center;">
  <h1>
    This is your Music TV
  </h1>
</div>
<nav style="text-align:center;">
  <button routerLink='/artists'>Artists</button>
  <button routerLink='/records'>Records</button>
</nav>
<router-outlet></router-outlet>
</div>

Now you can see that we have told the router to change the view to the Artists component when the “Artists” button is clicked, and do likewise when the “Records” button is clicked.

Finishing Touches

To add some style to the app so it stands out, open the app component CSS file and copy these rules inside it:

.car {
    top: 50%;
    text-align: center;
    border-radius: 25px;
    border: 2px solid #73AD21;
    padding: 20px;
    width: 600px;
    height: 250px;
    margin-left: 25%;
    margin-bottom: 15px;
  }
  
  button {
    top: 50%;
    text-align: center;
    border-radius: 15px;
    border: 2px solid #73AD21;
    width: fit-content;
    margin: 20px;
    padding: 20px;
  }

Save all these files and run the application on the dev server with:

ng serve

You will see that it runs exactly as it was shown above.

Wrapping up

We have just taken a look at the Angular Router and why it is important in your workflow, especially when building SPAs. We have seen how it is used and how we can easily navigate between views with it. I hope you incorporate routers in your workflow going forward. Happy hacking!


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 (2021-04-06T11:47:04+00:00) Angular Basics: Using the Router in Angular 12 to Navigate Views. Retrieved from https://www.scien.cx/2021/04/06/angular-basics-using-the-router-in-angular-12-to-navigate-views/

MLA
" » Angular Basics: Using the Router in Angular 12 to Navigate Views." Nwose Lotanna Victor | Sciencx - Tuesday April 6, 2021, https://www.scien.cx/2021/04/06/angular-basics-using-the-router-in-angular-12-to-navigate-views/
HARVARD
Nwose Lotanna Victor | Sciencx Tuesday April 6, 2021 » Angular Basics: Using the Router in Angular 12 to Navigate Views., viewed ,<https://www.scien.cx/2021/04/06/angular-basics-using-the-router-in-angular-12-to-navigate-views/>
VANCOUVER
Nwose Lotanna Victor | Sciencx - » Angular Basics: Using the Router in Angular 12 to Navigate Views. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/06/angular-basics-using-the-router-in-angular-12-to-navigate-views/
CHICAGO
" » Angular Basics: Using the Router in Angular 12 to Navigate Views." Nwose Lotanna Victor | Sciencx - Accessed . https://www.scien.cx/2021/04/06/angular-basics-using-the-router-in-angular-12-to-navigate-views/
IEEE
" » Angular Basics: Using the Router in Angular 12 to Navigate Views." Nwose Lotanna Victor | Sciencx [Online]. Available: https://www.scien.cx/2021/04/06/angular-basics-using-the-router-in-angular-12-to-navigate-views/. [Accessed: ]
rf:citation
» Angular Basics: Using the Router in Angular 12 to Navigate Views | Nwose Lotanna Victor | Sciencx | https://www.scien.cx/2021/04/06/angular-basics-using-the-router-in-angular-12-to-navigate-views/ |

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.