Pramod Patil
2 min readNov 28, 2019

--

Photo by Edouard Ki on Unplash

In this article, I am going to show you an easy way to set up Angular Dynamic Routing using Angular Router feature.

Step 1: Setup Project

Create Project using following Angular CLI command.

ng new article-routing

Step 2: Create Component

Open that project and create component using follwing command. ( if your using VS code use ctrl+` to open and close command prompt ).

ng g c article

Step 3: Setup Dyanamic Route

Open app-routing.module.ts file and add path name and component in “Routes” Array (app-routing.module.ts file created automatically in project when create project).

const routes: Routes = [
{
path:'',
component: ArticleComponent
},
{
path: 'article',
component: ArticleComponent,
children:[
{
path:'article/:type', //:type is dynamic here
component:ArticleComponent
}
]
}
];

Step 4: Import Router and create instance of Router in article Component

Open article.component.ts file and import Router and create instance of that.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'; //import router
@Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.css']
})
export class ArticleComponent implements OnInit {
constructor(public router:Router) { } //create instance
ngOnInit() {}
}

Step 5: Pass dynamically route type

open article.component.html file and write following logic. On every button click dynamic type parameter is passed using routerLink. And added condition on every paragrap ( <p> tag).

<h2>Article</h2><button type="button" routerLink='/article/trending'> Trending</button>&nbsp;
<button type="button" routerLink='/article/politics'> Politics</button>&nbsp;
<button type="button" routerLink='/article/business'> Business</button>&nbsp;
<button type="button" routerLink='/article/social'> Social</button>&nbsp;
<button type="button" routerLink='/article/bollywoodHollywood'> Bollywood/Hollywood</button>
<p *ngIf='router.url.includes("trending")'>Your are in Trending Section</p>
<p *ngIf='router.url.includes("politics")'>Your are in Politics Section</p>
<p *ngIf='router.url.includes("business")'>Your are in Business Section</p>
<p *ngIf='router.url.includes("social")'>Your are in Social Section</p>
<p *ngIf='router.url.includes("bollywoodHollywood")'>Your are in Bollywood/Hollywood Section</p>

Now , serve the project using Angular CLI command

ng serve

Now you can see changes on button click. (if you are a begineer , after ng serve , project will serve on localhost:4200 which is default port of angular)

--

--