0% found this document useful (0 votes)
2 views10 pages

Angular Router Setup and Navigation Guide

The Angular Router is a service that facilitates navigation between components based on URL paths, essential for building Single Page Applications (SPAs). It allows for dynamic routing, data passing through parameters, and programmatic navigation. The document outlines how to set up routing, manage components, and implement features such as child routes and data emission between components.

Uploaded by

Nïloy Ft Aminul
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Angular Router Setup and Navigation Guide

The Angular Router is a service that facilitates navigation between components based on URL paths, essential for building Single Page Applications (SPAs). It allows for dynamic routing, data passing through parameters, and programmatic navigation. The document outlines how to set up routing, manage components, and implement features such as child routes and data emission between components.

Uploaded by

Nïloy Ft Aminul
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is Angular Router?

The Angular Router is a built-in service that enables navigation between views
(components) based on URL paths.

It helps build Single Page Applications (SPAs) by:

• Loading different components on different routes

• Passing data through route parameters or query strings

• Navigating programmatically

How to Set Up a Route

1. App Routing Module ([Link])

Create or edit the routing module:

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


import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/[Link]';
import { ProductDetailComponent } from './products/[Link]';

const routes: Routes = [


{ path: '', component: HomeComponent },
{ path: 'product/:id', component: ProductDetailComponent }, // dynamic route
{ path: 'about', loadComponent: () => import('./about/[Link]').then(m =>
[Link]) }, // standalone component
];

@NgModule({
imports: [[Link](routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}2. Router Outlet in HTML
Place this in [Link] or your layout:

<router-outlet></router-outlet>
Navigate to a Route (Programmatic and HTML)

A. In HTML:

<a [routerLink]="['/product', 123]">View Product</a>

B. In Component (TypeScript):

import { Router } from '@angular/router';

constructor(private router: Router) {}

goToProduct(id: number) {

[Link](['/product', id]);

Get Current URL

From Component:

import { Router } from '@angular/router';

constructor(private router: Router) {

[Link]([Link]); // e.g., /product/123

Get Current Origin (Window Origin)

const origin = [Link];

[Link](origin); // e.g., [Link]

Get Last ID or Parameters from URL

In [Link]:

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {}


ngOnInit() {

const id = [Link]('id'); // '123'

[Link]('Product ID:', id);

Pass Multiple Data in URL

1. Using Path Parameters

Route:

{ path: 'user/:userId/order/:orderId', component: OrderComponent }

Navigate:

[Link](['/user', 5, 'order', 99]);

Read:

const userId = [Link]('userId');

const orderId = [Link]('orderId');

2. Using Query Parameters

Navigate:

[Link](['/search'], { queryParams: { q: 'laptop', page: 2 } });

Read:

[Link](params => {

const q = [Link]('q');

const page = [Link]('page');

});

Other Essentials for Angular Development

Core Router Imports:

import { RouterModule, Routes, Router, ActivatedRoute } from '@angular/router';


RouterLink Active for Navigation:

<a routerLink="/home" routerLinkActive="active">Home</a>

Redirects:

{ path: '', redirectTo: '/home', pathMatch: 'full' }

Wildcard Route (404):

{ path: '**', component: NotFoundComponent }


Concept Overview

You're building something like this:

• A main layout (MainLayoutComponent)

o Shows Header, Sidebar, router-outlet

• A ProductListComponent shows a grid of products

• When a product is clicked:

o A DrawerComponent slides in

o Inside it, ProductDetailComponent shows the selected product

• This is a single-page application (SPA):

o Page does not reload

o Different components are injected into the DOM dynamically

1. Project Structure (Simplified)

/app

/layouts

[Link]

/components

[Link]

[Link]

[Link]

/pages

[Link]

[Link]

[Link]

[Link]
2. Define Routes with Layout

// [Link]

const routes: Routes = [

path: '',

component: MainLayoutComponent,

children: [

{ path: '', component: HomeComponent },

{ path: 'products', component: ProductsComponent },

],

];

3. Layout HTML: Where Components Display

<!-- [Link] -->

<app-header></app-header>

<app-sidebar></app-sidebar>

<!-- Main content area -->

<div class="main-content">

<router-outlet></router-outlet>

</div>
4. Products Page with Child Components

<!-- [Link] -->

<app-product-list (selectProduct)="onProductSelected($event)"></app-product-list>

<!-- Conditionally show drawer -->

<app-product-drawer

*ngIf="selectedProduct"

[product]="selectedProduct"

(close)="onDrawerClose()">

</app-product-drawer>

// [Link]

export class ProductsComponent {

selectedProduct: any = null;

onProductSelected(product: any) {

[Link] = product;

onDrawerClose() {

[Link] = null;

}
5. Product List Component Emits Event

<!-- [Link] -->

<div *ngFor="let product of products" (click)="select(product)">

{{ [Link] }} - {{ [Link] }}

</div>

// [Link]

@Output() selectProduct = new EventEmitter<any>();

select(product: any) {

[Link](product);

6. Drawer Component Shows Detail

<!-- [Link] -->

<div class="drawer">

<button (click)="[Link]()">Close</button>

<app-product-detail [product]="product"></app-product-detail>

</div>

// [Link]

@Input() product: any;

@Output() close = new EventEmitter<void>();

7. Product Detail Component Displays Info

<!-- [Link] -->


<h2>{{ [Link] }}</h2>

<p>Price: {{ [Link] }}</p>

<p>Description: {{ [Link] }}</p>

// [Link]

@Input() product: any;

8. How It Works (Flow)

1. User navigates to /products

2. MainLayoutComponent loads and renders <router-outlet>

3. Inside router-outlet, ProductsComponent loads

4. ProductsComponent renders <app-product-list> and waits

5. User clicks a product → ProductListComponent emits selected product

6. ProductsComponent receives product and shows <app-product-drawer>

7. ProductDrawerComponent renders ProductDetailComponent with selected


product

8. User closes the drawer → emits close → drawer hides

No page reload. It’s all in one DOM page.

Bonus: If You Want to Use Routing to Open Drawer with a URL

You can add a child route like /products/:id and track route changes:

// [Link]

{ path: 'products/:id', component: ProductsComponent }

Then in ProductsComponent:

constructor(private route: ActivatedRoute) {}


ngOnInit() {

[Link](params => {

const id = [Link]('id');

if (id) {

// Fetch product by ID, then show in drawer

[Link] = [Link](id);

});

Then you can navigate to /products/10 and it will show the drawer with that product.

Summary Table

Task Angular Feature

Routing to load main page RouterModule, router-outlet

Load child components <app-xyz> with @Input/@Output

Emit data from child to parent @Output() + EventEmitter

Show drawer/modal *ngIf + CSS/Component

Pass data to drawer [product]="selectedProduct"

Route param for ID [Link]()

You might also like