How to set Routing in Angular2/4/5?

Routing means if you want to different from one (page/URL) to another (page/URL) without reloading page.
For Routing we need to import “Routes & RouterModule”. For implementing routing let first we create “app.routing.module.ts” file for defining URL for any component. In that we need to import routes from roter module of the angular. also display in below code.

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

import { LoginComponent } from "./pages/login/login.component";
import { TestComponent } from "./pages/test/test.component";

// Route config let's you map routes to components
const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: 'dashboard',  component: TestComponent }

  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
export class AppRoutingModule { }

In above code first we have to import ngModule & Router from the angular. Then we need to import component which we need to route. Then we need to create Array of that routes in that we have define default route with path parameter blank and redirect to your default component. Routing define with two parameter in object called path & component.

Then these Class need to import in app.module.ts like below code.

import { AppRoutingModule } from './app.routing.module';
imports: [ AppRoutingModule, ....]

You need to add  “<router-outlet></router-outlet>” in app.component.html file to display content that route.
Form these way we can easily implement routing for our application full process also display in below video.

For display Output run the npm start on terminal to run the application. then you can see out put like below.
default it load login component and then click test it will load test component code.

Any issue with setting Route please comment it below.

Spread the love
  • 22
  • 3