Basic Routing Concepts in Angular application

Let's understand what is routing, A routing is nothing but the navigating from one pages to another pages or when you needs to change the template view from one to another with the help of browser URL. Routing helps to build the single-page application(SPAs) and it's an significance of routing in angular application.

Routing concepts works based on the angular router, Now what is angular router, It is library of javascript implementation, Which it comes as part of angular core packaged as @angular/router ,

There's lot of essential events which i used in the router service with the help of an observable, Like

  1. NavigationStart.

  2. NavigationEnd.

  3. NavigationCancel.

  4. Scroll.

  5. ActivationStart.

  6. ActivationEnd.

  7. ResolveConfigLoadEnd.

As very first which i said routing enables that users to navigate from one page to another page or one view to another view.

A very first steps, You needs to import the RoutingModule in the application because the angular router contains the library package of all required services, directives and configurations.

 import { RoutingModule } from './routing/routing.module';

There are two way of method you can configure the application routes,

Method 1 : By using variable to refer to the routes of array and configuring for example

@NgModule({
       imports: [RouterModule.forRoot(routes)]
       exports : [RouterModule] 
})

Method 2 : Configuring inside the forRoot()

@NgModule({

 imports: [RouterModule.forRoot([
{ path: 'home',component:HomeComponent },
{ path: 'contact',component:ContactComponent },
{ path: "",redirectTo: 'home' },

])
       exports : [RouterModule] 
})

Activating the Routes

In order to access the routes on the template, We use the routerLink directive for link to display the page of view, The routes are activated with the router-outlet which is placed inside the template,

Example for routerLink

<a routerLink ="/home"> Home </a>
<a routerLink = "/contact">Contact</a>

You can also bind the routerLink directive inside the square brackets and use it as follow,

<a routerLink =["/home"]> Home </a>
<a routerLink = ["/contact"]>Contact</a>

Router Outlet

It is a directive used for placing the data on the template, And it act as a placeholder for putting component data in the view.

<router-outlets></router-outlets>

And it dones, now you can able to navigate from one page to anther page or change the template of view page.

This blog describes only the basic concepts of router only, But there are lot's of features and multiple router outlet out there like,

  1. Accessing the feature routes.

  2. Activating the route.

  3. Route order paths and modules.

  4. Using navigate() and navigateByUrl().

And that's it thanks for your time reading this blog!