ANGULAR ROUTING

Routing in any programming language is used to implement the navigation within the application.  For handling the navigation from 1 view page to another we use the routing. As a user, we need to move between different views that we have already defined. So for implementing these types of navigation we are using the routing.


So for implementing the routing we need to generate an Angular app with routing enabled. 

    ng new routing-app --routing


The above command will generate a new Angular application with the routing enabled in AppRoutingModule which is a NgModule where you can configure your routes


Now we need to add components for the routing


For adding the routing we need at least 2 components to navigate between pages. So for that, I am generating 2 components using the below commands

    ng g c first

    ng g c second


The CLI automatically appends Component, so if you were to write first-component, your component would be FirstComponentComponent. So please don`t append the component while generating.


Now we are going to import our components into AppRoutingModule as follows

import { FirstComponent } from './first/first.component';

import { SecondComponent } from './second/second.component';

Now we are defining the routes

Now we are going to import the AppRoutingModule into AppModule and add it to the imports array

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

import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module'; // CLI imports AppRoutingModule

import { AppComponent } from './app.component';

@NgModule({

  declarations: [

    AppComponent

  ],

  imports: [

    BrowserModule,

    AppRoutingModule // CLI adds AppRoutingModule to the AppModule's imports array

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }


Next, we are going to import  RouterModule and Routes into your routing module.


import { NgModule } from '@angular/core';

import { Routes, RouterModule } from '@angular/router'; // CLI imports router

import { FirstComponent } from './first/first.component';

import { SecondComponent } from './second/second.component';


const routes: Routes = [

{

    path: 'first',

    component: FirstComponent

  },

{

    path: 'second',

    component: SecondComponent

  }

]; // sets up routes constant where you define your routes


// configures NgModule imports and exports

@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }


So finally we completed the setting up of routing for angular applications  

Comments