Routing of an Angular Component | Angular Routing.


4 min read
Routing of an Angular Component | Angular Routing.

Routing means moving from one page to another page.
The Angular Router enables navigation from one view to the next when user clicks over the navigation links we provide.

Like Home, About, Contact-Us are the examples of links we mostly see in any website. Now, suppose user is at Home page and when user click over About button(link) that navigate us to About page, means it displayed us the content of About page and likewise.

Simply when user click the browser's back and forward buttons and the browser navigates backward and forward through the history of pages we have seen.

Angular Router

@angular/router is a JavaScript package that built and maintained by the Angular core team. The Angular router is a core part of the Angular platform. It enables developers to build Single Page Applications with multiple views and allow navigation between these views.

  • It provide possibility to have multiple router outlet.
  • Different path matching strategies.
  • Easy access to route parameters.
  • Route guards to protect components from unauthorized access.

#1 THE ROUTER-OUTLET

The Router-Outlet is a directive that’s available in router library @angular/router. Based on the current browser’s URL path the component is inserted into the <router-outlet>.

Suppose we have a routing for about 👇👇

{ path: 'about', component: AboutComponent }

Now, when the user opens localhost:port/about URL the AboutComponent will be inserted in <router-outlet>. This <router-outlet> is an HTML tag, we can paste this in app.component.html like this👇👇

<router-outlet></router-outlet>

We can have multiple outlets in our Angular application which enables us to implement advanced routing scenarios.

(Scroll down to read more about MULTIPLE OUTLETS AND AUXILIARY ROUTES)

#2 ROUTE MATCHING STRATEGIES

RouterModule.forRoot(routes) method is used to navigate the user to a specific view. we can have multiple routes like this👇👇

const routes: Routes = [
  // empty path
  { path: '', component: HomeComponent },
  
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact-us', component: ContactUsComponent },
  
  // path with parameter
  { path: 'user/:id', component: UserDetailComponent },
  
  // wildcard path
  { path: '**', component: PageNotFoundComponent }
];
  • We can also have empty path which denotes the default path of an application. It opens when application starts, example localhost:port/ or http://www.codewithchintan.com
  • The :id is a token for a route parameter. In a URL such as /user/31, "31" is the value of the id parameter. The corresponding UserDetailComponent will use that value to find and present the user details whose id is 31.
  • Wildcard string (**) in this a path can take any string, this calls when the requested URL doesn’t match any paths for the defined routes. This can be used for displaying a “Page Not Found” view or redirecting to a specific view if no match is found.

#3 ROUTE GUARDS

Route-Guards allows or denies the user access to the route pages.

  • It is very much important in application having login/logout scenarios. We can easily manage which page is allowed for logged in user and which for non-logged in users.
  • 'Route-Guards' is an Important and quite ‘Implementation part’ that is the reason we covered this topic in separate article.
    Read here about How to implement ROUTE GUARDS (Click here 👆)

#4 NAVIGATION DIRECTIVE

routerLink is a directive to create navigation links this directive takes the associated path and navigate to the component. For example:

<a [routerLink]="'/about'">About Us</a>

The Angular Router match this path from routing and takes us to the matched component: (In this case /about this will take us to AboutComponent 👇👇)

{ path: 'about', component: AboutComponent }

#5 MULTIPLE OUTLETS AND AUXILIARY ROUTES

We can have multiple outlets in same application like this:👇👇
(This <router-outlet> is an HTML tag, we can paste this in app.component.html  or any other component like this👇👇)

<router-outlet></router-outlet>  
<router-outlet name="outlet2"></router-outlet> 

A component has one primary route and we can have auxiliary routes.
Auxiliary routes enable developers to navigate to multiple routes at the same time.

We need to name a router outlet to create an auxiliary route then the component associated with the auxiliary route will be displayed.

  • The outlet without a name is the primary outlet.
  • All other outlets must have a name except the primary outlet.

Next in the router navigation we need to specify the outlet attribute, like this:

{ path: 'about', component: AboutComponent, outlet: 'outlet2' }

#6 FINAL CODE

#6.1 CREATING A ROUTING MODULE

We will create routing module.
Open up your src/app/app-routing.module.ts file and update it as follows:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

// we define a constant routes array of type Routes
// this will hold information for each route
const routes: Routes = [
  // empty path
  { path: '', component: HomeComponent },
  
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact-us', component: ContactUsComponent },
  
  // path with parameter
  { path: 'user/:id', component: UserDetailComponent },
  
  // wildcard path
  { path: '**', component: PageNotFoundComponent }
];


@NgModule({
  // Its a RouterModule static methods forRoot() here we pass routes object
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

#6.2 IMPORTING THE ROUTING MODULE

Next, we need to import this routing module into the main app module.
Open up your src/app/app.module.ts file and update it as follows:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

// importing app-routing-module
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    // add app-routing-module in imports array
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

#6.3 ADDING THE ROUTER OUTLET

Final step is to add the router outlet.
Open up your src/app/app.component.html file (which contains the main app template) and add the <router-outlet> component. Update it as follows:

<router-outlet></router-outlet>

The Angular router replaces this <router-outlet></router-outlet> with the component that matched in your routing.

{ path: 'about', component: AboutComponent }

So, in above case when user opens /about page the <router-outlet></router-outlet> tag replaced by the template of AboutComponent.


#7 ROUTING REDIRECT

We can also redirect to another route, this is how we can do that👇👇
(we can leave the path empty or we can specify the path value)

{ path: '', pathMatch: 'full', redirectTo: 'contact-us' }  

Here we want to match the exact empty path, that’s why we specify the full match strategy.


Conclusion

  • First we understand about 'Angular Router'.
  • Then covered the concept of ROUTER-OUTLET.
  • Then ROUTE MATCHING STRATEGIES.
  • Then ROUTE GUARDS.
  • Then NAVIGATION DIRECTIVE.
  • Then MULTIPLE OUTLETS AND AUXILIARY ROUTES.
  • Finally, The FINAL CODE.
  • We can also do ROUTING REDIRECT.

Done! 🤩
The concept 'Routing of an Angular Component' was so simple.

See you later 👋👋 bye.. bye..


Feel free to comment down in the comment box… If I missed anything or anything is incorrect or anything does not works for you :)
Stay connected for more articles.

GO TOP

🎉 You've successfully subscribed to Code with Chintan!
OK