(Go: >> BACK << -|- >> HOME <<)

SlideShare a Scribd company logo
How to Implement
Basic Angular
Routing and
Nested Routing
With Params in
Angular v11
www.bacancytechnology.com
Table of Index
1. Introduction
2. Goal
3. Github Repository for Angular routing
example
4. Install Angular CLI
5. Create and configure the Angular project
6. Implement Basic Angular Routing in
Angular Version 11
7. Nested Angular Routing and Angular
Routing with Params in Angular v11
8. Conclusion
Introduction
When you are going through any website,
have you ever wondered why and how you
are redirected to the Home page and not the
About Us page while clicking the home link?
The whole mechanism that decides what
should be displayed when the user takes
action is termed routing. You might be
familiar with the jargon if you have already
worked with any front-end frameworks.
Even if you haven’t, then that’s completely
fine; because this blog will help you with
steps to implement Angular routing and a
Github repo also to come out of your
‘beginner zone.’
Let’s get started with How Routing Works
in Angular 11.
Goal
Before knowing how to build, let’s know
what to build.
Here’s the video of demo which we would
be developing in this blog-
Github
Repository
for Angular
v11 Routing
Example
Click here to visit the Github Repository
OR
Open Terminal and run this command to
clone the repository
git clone
https://github.com/architanayak/angular-
routing.git
Okay, so now you’re aware of what are we
developing, and as a bonus, you have a
github repository to clone and play around
with the demo. Let’s start the steps from
installing the Angular project to implement
the Angular routing in Angular version 11.
Install
Angular CLI
Use the below-mentioned command to
install the latest version of Angular CLI in
your system.
Globally-
npm install -g @angular/cli
Locally-
npm install @angular/cli
To verify the installation, run the following
command-
ng --version
The command will show you the version of
Angular that you’ve just installed. You will
see something like this on your terminal.
Create and
Configure
Angular
project
After the installation is done, we will create
a brand new Angular project and configure
it accordingly.
ng new demo-app
NOTE- You can name it whatever you want
instead of demo-app
Answer the series of questions, and you will
successfully create your project. Make sure
that you choose YES for – Would you like to
add Angular routing?
⦿Create an Angular project.
Need support for routing and
navigation in Angular 11?
Hire Angular developers from us to keep
your Angular project up-to-date,
implementing latest features to the stable
release.
Implement Now
Project structure-
Generate components for Home, Marvel
movies, and DC movies using these
commands, respectively.
ng g c home
ng g c marvel-movies
ng g c dc-movies
⦿Configure your project
After running the commands, check your
src/app. The project structure will look like this-
src/app
NOTE- The project structure can vary according
to demo.
npm install bootstrap --save
npm install --save @ng-bootstrap/ng-
bootstrap
ng add @ng-bootstrap/ng-bootstrap
Once you have implemented all the above
commands open app.module.ts, and you’ll
notice that the components and ng-
bootstrap library has been imported and
declared automatically.
⦿Install ng-bootstrap –
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from
'@angular/platform-browser';
import {NgbModule} from '@ng-
bootstrap/ng-bootstrap';
import { AppRoutingModule } from './app-
routing.module';
import { AppComponent } from
'./app.component';
import { HomeComponent } from
'./home/home.component';
import { MarvelMoviesComponent } from
'./marvel-movies/marvel-
movies.component';
import { DCMoviesComponent } from './dc-
movies/dc-movies.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
MarvelMoviesComponent,
DCMoviesComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Moving towards the next section, i.e., Basic
Angular routing.
Implement
Basic Angular
routing in
Angular
Version 11
We will be changing these two files-
⦾ app-routing.module.ts
⦾ app.component.html
⦾ app-routing.module.ts
In this file we will declare route with their
respective components. So, the application
would know which component has to be
rendered on which route.
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from
'@angular/router';
import { HomeComponent } from
'./home/home.component';
import { MarvelMoviesComponent } from
'./marvel-movies/marvel-
movies.component';
import { DCMoviesComponent } from './dc-
movies/dc-movies.component';
const routes: Routes = [
{
path: '',
redirectTo: '/home',
pathMatch: 'full',
},
{
path: 'home',
component: HomeComponent,
},
{
path: 'marvel-movies',
component: MarvelMoviesComponent
},
{
path: 'dc-movies',
component: DCMoviesComponent,
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Explanation-
{
path: '',
redirectTo: '/home',
pathMatch: 'full',
},
Due to this above-mentioned code snippet,
the site will be redirected to ‘/home’ when
the application is launched, i.e., the
component will render at ‘/home’ as your
default page.
{
path: 'home',
component: HomeComponent,
},
This code snippet indicates that
HomeComponent is displayed on URL
‘/home’
The logic works same for other two
components – MarvelMoviesComponent
and DCMoviesomponent
⦾ app.component.html
The components are always rendered with
the help of Router-Outlet of the parent
component. And as app.component.html is
the parent component of all the
components, we will have the links for
home page, marvel movies page, and dc
movies page here.
app.component.html
<div class="container">
<nav class="navbar navbar-expand-lg
navbar-light bg-light">
<div class="collapse navbar-collapse
header-nav" id="navbarNav">
<ul class="navbar-nav" >
<li class="nav-item" >
<a class="nav-link" [routerLink]="
['/home']">
Home
</a >
</li>
<li class="nav-item">
<a class="nav-link" [routerLink]="
['/marvel-movies']">
Marvel Movies
</a>
</li>
<li class="nav-item">
<a class="nav-link" [routerLink]="['/dc-
movies']">
DC Movies
</a>
</li>
</ul>
</div>
<span class="navbar-brand">Angular 11
Routing</span>
</nav>
</div>
<router-outlet ></router-outlet>
Open the localhost and try whether you’ve
done the routing correctly or not. It should
be something like this (omitting the design
part)-
NOTE: Here, I have changed the text in dc-
movies.component.html and marvel-
movies.component.html. You might see the
default texts for both components. And
plus, to keep it simple for beginners I have
not made a common component for Marvel
and DC rather I have used similar codes for
both the components. You can choose to
create a single component for both.
So, this was an example and explanation of
Basic Angular routing. Now, taking one
more step ahead and see how to implement
Nested Routing and Routing with params.
We are going to give you an
Offer,
That you can’t resist…
Hire Dedicated Angular Developer
&#038; Start Your Free Trial Now!
Nested
Angular
Routing and
Angular
Routing with
Params in
Angular v11
Run below mentioned command to create
MovieDetail component.
ng g c movie-detail
Your project structure in the app folder will
be updated with this-
Now, let’s start coding.
1. Modifying the existing components –
Marvel Movies and DC Movies
As we need to change our Angular UI we
will add the following lines of code in these
files.
Marvel-movies
marvel-movies.component.ts ->Define a
static array of movie objects.
marvel-movies.component.ts
import { Component, OnInit } from
'@angular/core';
@Component({
selector: 'app-marvel-movies',
templateUrl: './marvel-
movies.component.html',
styleUrls: ['./marvel-
movies.component.css']
})
export class MarvelMoviesComponent
implements OnInit {
public movies = [
{
id: "1",
name: "CAPTAIN AMERICA: THE FIRST
AVENGER",
},
{
id: "2",
name: "DOCTOR STRANGE",
},
{
id: "3",
name: "IRON MAN",
}
]
constructor() { }
ngOnInit(): void {
}
}
marvel-movies.component.html -> Display
each movie by using *ngFor.
marvel-movies.component.html
<div *ngFor="let movie of movies; let i =
index">
<button type="button"
class="btn btn-primary btn-lg btn-block"
[routerLink]="movie.id"
[state]="movie"
>
{{movie.name}}
</button>
</div>
You can apply same code in the files (dc-
movies.component.html, dc-
movies.component.ts) of the component dc-
movies
2. Modifying the file of Movie detail
component
movie-detail.component.ts
import { Component, OnInit } from
'@angular/core';
import { ActivatedRoute } from
'@angular/router';
@Component({
selector: 'app-movie-detail',
templateUrl: './movie-
detail.component.html',
styleUrls: ['./movie-detail.component.css']
})
export class MovieDetailComponent
implements OnInit {
public movieId;
public movieData;
constructor(private activatedRoute:
ActivatedRoute) {
}
ngOnInit() {
// to access data of movie
this.movieData = history.state
// to access params
this.movieId =
this.activatedRoute.snapshot.params.id;
console.log("Params movieId",
this.movieId);
}
}
You might have guessed from the above
snippet, what’s the exact use of
ActivatedRoute. But if not, do not
worry. Basically, ActivatedRoute helps
us to get the route data. Suppose, if a
situation arises, that we want to have a
dynamic parameter in a route. For eg:
/users/1 , /users/2 …. So here the /users/
is common, but the id gets updated. And
if I want to fetch the data user-wise, we
need to fetch the id from the URL. So to
handle such scenarios, ActivatedRoute
comes as a rescue.
We can access route data in two ways :
Explanation:
* Using Snapshot
* Using Observable (Subscribe).
I have shown (1) in the above snippet.
Use the Snapshot if you are pretty sure
that you need an initial value of the
parameter and the value would not
change from the same component. As
the name suggests, it would give you a
snapshot of the initial value and would
not catch the change after it.
Use the Observable if there are chances
of change in the value of the parameter
from the same component. As we are
using observable, it would catch each
change till we unsubscribe from it. If
you are not sure about which to use, the
safest option is to use the Observable.
You can use history.state to access the
information about the selected movie
and display it. Rather than that, if you
have a different .json file, you can get
the id from activatedRoute (here
movieId) and then filter the data based
on the id.
3. Modifying the file related to Routing
app-routing.module.ts
Import this –
import { MovieDetailComponent } from
'./movie-detail/movie-detail.component';
Change the routes for Marvel and DC
movies-
const routes: Routes = [
{
path: '',
redirectTo: '/home',
pathMatch: 'full',
},
{
path: 'home',
component: HomeComponent,
},
{
path: 'marvel-movies',
children: [
{
path: '',
component: MarvelMoviesComponent
},
{
path: ':id',
component: MovieDetailComponent
}
]
},
{
path: 'dc-movies',
children: [
{
path: '',
component: DCMoviesComponent,
},
{
path: ':id',
component: MovieDetailComponent
}
]
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
children attribute consist of various
child routes, which you want to add
after /marvel-movies.
When the URL matches route /marvel-
movies, MarvelMoviesComponent is
displayed because of this –
Explanation –
{
path: '',
component: MarvelMoviesComponent
},
When the URL matches route- /marvel-
movies/:id, MovieDetailComponent is
displayed because of this-
{
path: ':id',
component: MovieDetailComponent
}
You can apply the same lines of code for DC
movies component too.
Your localhost will look something like this
if you have implemented the code as
directed above (omitting the design part).
So far, so good? This was all about Basic
Angular Routing and Nested Angular
Routing, and Angular Routing with params
in Angular v11. In next blog, I will let you
know how to load the routes lazily.
Even after developing various demo you
might need help when you want to
implement Angular app router in Angular
v11 for large-scaled Angular projects. And
for that, we are to lend a helping hand.
Without wasting a single minute connect to
Bacancy Technology to work with best
Angular developers. To fulfill your varied
project requirements, we let you hire
Angular developer from us at your
convenience who have in-depth knowledge
and extensive expertise in dealing with all
the shapes and sizes of Angular projects.
Conclusion
Thank You
www.bacancytechnology.com

More Related Content

What's hot

Flutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfFlutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdf
Katy Slemon
 
Tech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkTech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new framework
Codemotion
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
Knoldus Inc.
 
Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0 Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0
Sumanth Chinthagunta
 
Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1
Ahmed Moawad
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developers
Yakov Fain
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation
Phan Tuan
 
Angular js 2
Angular js 2Angular js 2
Angular js 2
Ran Wahle
 
Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2
Ahmed Moawad
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
Patrick Schroeder
 
Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)
Katy Slemon
 
Introduction to angular 4
Introduction to angular 4Introduction to angular 4
Introduction to angular 4
Marwane El Azami
 
Angularjs
AngularjsAngularjs
Angularjs
Vincenzo Ferrari
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
Nir Kaufman
 
Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
 
AngularJS - Services
AngularJS - ServicesAngularJS - Services
AngularJS - Services
Nir Kaufman
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
Yakov Fain
 
Angular from Scratch
Angular from ScratchAngular from Scratch
Angular from Scratch
Christian Lilley
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
Jadson Santos
 
Migrating an application from Angular 1 to Angular 2
Migrating an application from Angular 1 to Angular 2 Migrating an application from Angular 1 to Angular 2
Migrating an application from Angular 1 to Angular 2
Ross Dederer
 

What's hot (20)

Flutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdfFlutter State Management Using GetX.pdf
Flutter State Management Using GetX.pdf
 
Tech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new frameworkTech Webinar: Angular 2, Introduction to a new framework
Tech Webinar: Angular 2, Introduction to a new framework
 
Introduction to Angular 2
Introduction to Angular 2Introduction to Angular 2
Introduction to Angular 2
 
Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0 Single Page Applications with AngularJS 2.0
Single Page Applications with AngularJS 2.0
 
Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1Exploring Angular 2 - Episode 1
Exploring Angular 2 - Episode 1
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developers
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation
 
Angular js 2
Angular js 2Angular js 2
Angular js 2
 
Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2Exploring Angular 2 - Episode 2
Exploring Angular 2 - Episode 2
 
Angular 2 Essential Training
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
 
Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)Build a video chat application with twilio, rails, and javascript (part 1)
Build a video chat application with twilio, rails, and javascript (part 1)
 
Introduction to angular 4
Introduction to angular 4Introduction to angular 4
Introduction to angular 4
 
Angularjs
AngularjsAngularjs
Angularjs
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
Angular 8
Angular 8 Angular 8
Angular 8
 
AngularJS - Services
AngularJS - ServicesAngularJS - Services
AngularJS - Services
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
 
Angular from Scratch
Angular from ScratchAngular from Scratch
Angular from Scratch
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Migrating an application from Angular 1 to Angular 2
Migrating an application from Angular 1 to Angular 2 Migrating an application from Angular 1 to Angular 2
Migrating an application from Angular 1 to Angular 2
 

Similar to How to Implement Basic Angular Routing and Nested Routing With Params in Angular v11

Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Frost
 
Angular IO
Angular IOAngular IO
Angular IO
Jennifer Estrada
 
mean stack
mean stackmean stack
mean stack
michaelaaron25322
 
Web worker in your angular application
Web worker in your angular applicationWeb worker in your angular application
Web worker in your angular application
Suresh Patidar
 
An Overview of Angular 4
An Overview of Angular 4 An Overview of Angular 4
Peggy angular 2 in meteor
Peggy   angular 2 in meteorPeggy   angular 2 in meteor
Peggy angular 2 in meteor
LearningTech
 
Voorhoede - Front-end architecture
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architecture
Jasper Moelker
 
Server-Side Rendering (SSR) with Angular Universal
Server-Side Rendering (SSR) with Angular UniversalServer-Side Rendering (SSR) with Angular Universal
Server-Side Rendering (SSR) with Angular Universal
Katy Slemon
 
Angular components
Angular componentsAngular components
Angular components
Sultan Ahmed
 
Angular routing
Angular routingAngular routing
Angular routing
Sultan Ahmed
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdf
JohnLeo57
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
Bipin
 
Angular4 getting started
Angular4 getting startedAngular4 getting started
Angular4 getting started
TejinderMakkar
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Digamber Singh
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
Keith Bloomfield
 
Jan 2017 - a web of applications (angular 2)
Jan 2017 - a web of applications (angular 2)Jan 2017 - a web of applications (angular 2)
Jan 2017 - a web of applications (angular 2)
Kasper Reijnders
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
Nir Kaufman
 
Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...
Katy Slemon
 
Angular Notes.pdf
Angular Notes.pdfAngular Notes.pdf
Angular Notes.pdf
sagarpal60
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 

Similar to How to Implement Basic Angular Routing and Nested Routing With Params in Angular v11 (20)

Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
Angular IO
Angular IOAngular IO
Angular IO
 
mean stack
mean stackmean stack
mean stack
 
Web worker in your angular application
Web worker in your angular applicationWeb worker in your angular application
Web worker in your angular application
 
An Overview of Angular 4
An Overview of Angular 4 An Overview of Angular 4
An Overview of Angular 4
 
Peggy angular 2 in meteor
Peggy   angular 2 in meteorPeggy   angular 2 in meteor
Peggy angular 2 in meteor
 
Voorhoede - Front-end architecture
Voorhoede - Front-end architectureVoorhoede - Front-end architecture
Voorhoede - Front-end architecture
 
Server-Side Rendering (SSR) with Angular Universal
Server-Side Rendering (SSR) with Angular UniversalServer-Side Rendering (SSR) with Angular Universal
Server-Side Rendering (SSR) with Angular Universal
 
Angular components
Angular componentsAngular components
Angular components
 
Angular routing
Angular routingAngular routing
Angular routing
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdf
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
 
Angular4 getting started
Angular4 getting startedAngular4 getting started
Angular4 getting started
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
 
Jan 2017 - a web of applications (angular 2)
Jan 2017 - a web of applications (angular 2)Jan 2017 - a web of applications (angular 2)
Jan 2017 - a web of applications (angular 2)
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...
 
Angular Notes.pdf
Angular Notes.pdfAngular Notes.pdf
Angular Notes.pdf
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 

Recently uploaded

How Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global ScaleHow Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global Scale
ScyllaDB
 
Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024
The Digital Insurer
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
shanthidl1
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
Mark Billinghurst
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
Safe Software
 
Hire a private investigator to get cell phone records
Hire a private investigator to get cell phone recordsHire a private investigator to get cell phone records
Hire a private investigator to get cell phone records
HackersList
 
AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)
apoorva2579
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Mydbops
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
amitchopra0215
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
Matthew Sinclair
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
Stephanie Beckett
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
jackson110191
 
Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1
FellyciaHikmahwarani
 
GDG Cloud Southlake #34: Neatsun Ziv: Automating Appsec
GDG Cloud Southlake #34: Neatsun Ziv: Automating AppsecGDG Cloud Southlake #34: Neatsun Ziv: Automating Appsec
GDG Cloud Southlake #34: Neatsun Ziv: Automating Appsec
James Anderson
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
Lessons Of Binary Analysis - Christien Rioux
Lessons Of Binary Analysis - Christien RiouxLessons Of Binary Analysis - Christien Rioux
Lessons Of Binary Analysis - Christien Rioux
crioux1
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
Aurora Consulting
 
Data Protection in a Connected World: Sovereignty and Cyber Security
Data Protection in a Connected World: Sovereignty and Cyber SecurityData Protection in a Connected World: Sovereignty and Cyber Security
Data Protection in a Connected World: Sovereignty and Cyber Security
anupriti
 
Blockchain and Cyber Defense Strategies in new genre times
Blockchain and Cyber Defense Strategies in new genre timesBlockchain and Cyber Defense Strategies in new genre times
Blockchain and Cyber Defense Strategies in new genre times
anupriti
 

Recently uploaded (20)

How Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global ScaleHow Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global Scale
 
Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
 
Hire a private investigator to get cell phone records
Hire a private investigator to get cell phone recordsHire a private investigator to get cell phone records
Hire a private investigator to get cell phone records
 
AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
 
Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1
 
GDG Cloud Southlake #34: Neatsun Ziv: Automating Appsec
GDG Cloud Southlake #34: Neatsun Ziv: Automating AppsecGDG Cloud Southlake #34: Neatsun Ziv: Automating Appsec
GDG Cloud Southlake #34: Neatsun Ziv: Automating Appsec
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
Lessons Of Binary Analysis - Christien Rioux
Lessons Of Binary Analysis - Christien RiouxLessons Of Binary Analysis - Christien Rioux
Lessons Of Binary Analysis - Christien Rioux
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
 
Data Protection in a Connected World: Sovereignty and Cyber Security
Data Protection in a Connected World: Sovereignty and Cyber SecurityData Protection in a Connected World: Sovereignty and Cyber Security
Data Protection in a Connected World: Sovereignty and Cyber Security
 
Blockchain and Cyber Defense Strategies in new genre times
Blockchain and Cyber Defense Strategies in new genre timesBlockchain and Cyber Defense Strategies in new genre times
Blockchain and Cyber Defense Strategies in new genre times
 

How to Implement Basic Angular Routing and Nested Routing With Params in Angular v11

  • 1. How to Implement Basic Angular Routing and Nested Routing With Params in Angular v11 www.bacancytechnology.com
  • 2. Table of Index 1. Introduction 2. Goal 3. Github Repository for Angular routing example 4. Install Angular CLI 5. Create and configure the Angular project 6. Implement Basic Angular Routing in Angular Version 11 7. Nested Angular Routing and Angular Routing with Params in Angular v11 8. Conclusion
  • 4. When you are going through any website, have you ever wondered why and how you are redirected to the Home page and not the About Us page while clicking the home link? The whole mechanism that decides what should be displayed when the user takes action is termed routing. You might be familiar with the jargon if you have already worked with any front-end frameworks. Even if you haven’t, then that’s completely fine; because this blog will help you with steps to implement Angular routing and a Github repo also to come out of your ‘beginner zone.’
  • 5. Let’s get started with How Routing Works in Angular 11.
  • 7. Before knowing how to build, let’s know what to build. Here’s the video of demo which we would be developing in this blog-
  • 9. Click here to visit the Github Repository OR Open Terminal and run this command to clone the repository git clone https://github.com/architanayak/angular- routing.git Okay, so now you’re aware of what are we developing, and as a bonus, you have a github repository to clone and play around with the demo. Let’s start the steps from installing the Angular project to implement the Angular routing in Angular version 11.
  • 11. Use the below-mentioned command to install the latest version of Angular CLI in your system. Globally- npm install -g @angular/cli Locally- npm install @angular/cli To verify the installation, run the following command- ng --version
  • 12. The command will show you the version of Angular that you’ve just installed. You will see something like this on your terminal.
  • 14. After the installation is done, we will create a brand new Angular project and configure it accordingly. ng new demo-app NOTE- You can name it whatever you want instead of demo-app Answer the series of questions, and you will successfully create your project. Make sure that you choose YES for – Would you like to add Angular routing? ⦿Create an Angular project.
  • 15. Need support for routing and navigation in Angular 11? Hire Angular developers from us to keep your Angular project up-to-date, implementing latest features to the stable release. Implement Now
  • 16. Project structure- Generate components for Home, Marvel movies, and DC movies using these commands, respectively. ng g c home ng g c marvel-movies ng g c dc-movies ⦿Configure your project
  • 17. After running the commands, check your src/app. The project structure will look like this- src/app NOTE- The project structure can vary according to demo.
  • 18. npm install bootstrap --save npm install --save @ng-bootstrap/ng- bootstrap ng add @ng-bootstrap/ng-bootstrap Once you have implemented all the above commands open app.module.ts, and you’ll notice that the components and ng- bootstrap library has been imported and declared automatically. ⦿Install ng-bootstrap –
  • 19. app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import {NgbModule} from '@ng- bootstrap/ng-bootstrap'; import { AppRoutingModule } from './app- routing.module'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { MarvelMoviesComponent } from './marvel-movies/marvel- movies.component'; import { DCMoviesComponent } from './dc- movies/dc-movies.component'; @NgModule({ declarations: [
  • 20. AppComponent, HomeComponent, MarvelMoviesComponent, DCMoviesComponent, ], imports: [ BrowserModule, AppRoutingModule, NgbModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Moving towards the next section, i.e., Basic Angular routing.
  • 22. We will be changing these two files- ⦾ app-routing.module.ts ⦾ app.component.html ⦾ app-routing.module.ts In this file we will declare route with their respective components. So, the application would know which component has to be rendered on which route.
  • 23. app-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { MarvelMoviesComponent } from './marvel-movies/marvel- movies.component'; import { DCMoviesComponent } from './dc- movies/dc-movies.component'; const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full', }, { path: 'home', component: HomeComponent,
  • 24. }, { path: 'marvel-movies', component: MarvelMoviesComponent }, { path: 'dc-movies', component: DCMoviesComponent, }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
  • 25. Explanation- { path: '', redirectTo: '/home', pathMatch: 'full', }, Due to this above-mentioned code snippet, the site will be redirected to ‘/home’ when the application is launched, i.e., the component will render at ‘/home’ as your default page. { path: 'home', component: HomeComponent, },
  • 26. This code snippet indicates that HomeComponent is displayed on URL ‘/home’ The logic works same for other two components – MarvelMoviesComponent and DCMoviesomponent ⦾ app.component.html The components are always rendered with the help of Router-Outlet of the parent component. And as app.component.html is the parent component of all the components, we will have the links for home page, marvel movies page, and dc movies page here.
  • 27. app.component.html <div class="container"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="collapse navbar-collapse header-nav" id="navbarNav"> <ul class="navbar-nav" > <li class="nav-item" > <a class="nav-link" [routerLink]=" ['/home']"> Home </a > </li> <li class="nav-item"> <a class="nav-link" [routerLink]=" ['/marvel-movies']"> Marvel Movies </a> </li> <li class="nav-item"> <a class="nav-link" [routerLink]="['/dc- movies']">
  • 28. DC Movies </a> </li> </ul> </div> <span class="navbar-brand">Angular 11 Routing</span> </nav> </div> <router-outlet ></router-outlet>
  • 29. Open the localhost and try whether you’ve done the routing correctly or not. It should be something like this (omitting the design part)-
  • 30. NOTE: Here, I have changed the text in dc- movies.component.html and marvel- movies.component.html. You might see the default texts for both components. And plus, to keep it simple for beginners I have not made a common component for Marvel and DC rather I have used similar codes for both the components. You can choose to create a single component for both. So, this was an example and explanation of Basic Angular routing. Now, taking one more step ahead and see how to implement Nested Routing and Routing with params.
  • 31. We are going to give you an Offer, That you can’t resist… Hire Dedicated Angular Developer &#038; Start Your Free Trial Now!
  • 33. Run below mentioned command to create MovieDetail component. ng g c movie-detail
  • 34. Your project structure in the app folder will be updated with this- Now, let’s start coding. 1. Modifying the existing components – Marvel Movies and DC Movies As we need to change our Angular UI we will add the following lines of code in these files.
  • 35. Marvel-movies marvel-movies.component.ts ->Define a static array of movie objects. marvel-movies.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-marvel-movies', templateUrl: './marvel- movies.component.html', styleUrls: ['./marvel- movies.component.css'] }) export class MarvelMoviesComponent implements OnInit { public movies = [ {
  • 36. id: "1", name: "CAPTAIN AMERICA: THE FIRST AVENGER", }, { id: "2", name: "DOCTOR STRANGE", }, { id: "3", name: "IRON MAN", } ] constructor() { } ngOnInit(): void { } }
  • 37. marvel-movies.component.html -> Display each movie by using *ngFor. marvel-movies.component.html <div *ngFor="let movie of movies; let i = index"> <button type="button" class="btn btn-primary btn-lg btn-block" [routerLink]="movie.id" [state]="movie" > {{movie.name}} </button> </div>
  • 38. You can apply same code in the files (dc- movies.component.html, dc- movies.component.ts) of the component dc- movies 2. Modifying the file of Movie detail component movie-detail.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-movie-detail', templateUrl: './movie- detail.component.html', styleUrls: ['./movie-detail.component.css'] })
  • 39. export class MovieDetailComponent implements OnInit { public movieId; public movieData; constructor(private activatedRoute: ActivatedRoute) { } ngOnInit() { // to access data of movie this.movieData = history.state // to access params this.movieId = this.activatedRoute.snapshot.params.id; console.log("Params movieId", this.movieId); } }
  • 40. You might have guessed from the above snippet, what’s the exact use of ActivatedRoute. But if not, do not worry. Basically, ActivatedRoute helps us to get the route data. Suppose, if a situation arises, that we want to have a dynamic parameter in a route. For eg: /users/1 , /users/2 …. So here the /users/ is common, but the id gets updated. And if I want to fetch the data user-wise, we need to fetch the id from the URL. So to handle such scenarios, ActivatedRoute comes as a rescue. We can access route data in two ways : Explanation: * Using Snapshot * Using Observable (Subscribe). I have shown (1) in the above snippet.
  • 41. Use the Snapshot if you are pretty sure that you need an initial value of the parameter and the value would not change from the same component. As the name suggests, it would give you a snapshot of the initial value and would not catch the change after it. Use the Observable if there are chances of change in the value of the parameter from the same component. As we are using observable, it would catch each change till we unsubscribe from it. If you are not sure about which to use, the safest option is to use the Observable. You can use history.state to access the information about the selected movie and display it. Rather than that, if you have a different .json file, you can get the id from activatedRoute (here movieId) and then filter the data based on the id.
  • 42. 3. Modifying the file related to Routing app-routing.module.ts Import this – import { MovieDetailComponent } from './movie-detail/movie-detail.component'; Change the routes for Marvel and DC movies- const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full', }, { path: 'home', component: HomeComponent, }, {
  • 43. path: 'marvel-movies', children: [ { path: '', component: MarvelMoviesComponent }, { path: ':id', component: MovieDetailComponent } ] }, { path: 'dc-movies', children: [ { path: '', component: DCMoviesComponent, }, { path: ':id', component: MovieDetailComponent
  • 45. children attribute consist of various child routes, which you want to add after /marvel-movies. When the URL matches route /marvel- movies, MarvelMoviesComponent is displayed because of this – Explanation – { path: '', component: MarvelMoviesComponent },
  • 46. When the URL matches route- /marvel- movies/:id, MovieDetailComponent is displayed because of this- { path: ':id', component: MovieDetailComponent } You can apply the same lines of code for DC movies component too. Your localhost will look something like this if you have implemented the code as directed above (omitting the design part).
  • 47. So far, so good? This was all about Basic Angular Routing and Nested Angular Routing, and Angular Routing with params in Angular v11. In next blog, I will let you know how to load the routes lazily.
  • 48. Even after developing various demo you might need help when you want to implement Angular app router in Angular v11 for large-scaled Angular projects. And for that, we are to lend a helping hand. Without wasting a single minute connect to Bacancy Technology to work with best Angular developers. To fulfill your varied project requirements, we let you hire Angular developer from us at your convenience who have in-depth knowledge and extensive expertise in dealing with all the shapes and sizes of Angular projects. Conclusion