You are on page 1of 5

create app-routing module

ng generate module app-routing --flat --module=app

================================
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HeroesComponent } from './heroes/heroes.component';

const routes: Routes = [


{ path: 'heroes', component: HeroesComponent }
];

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

===============

explain Routes -- path, component


==================================
RouterModule.forRoot(routes)
==================================
export RouterModule -> to provide router module throughout the app
==================================
RouterOutlet <router-outlet></router-outlet> a router diective
==================================

add roterLink
<a routerLink="/heroes">Heroes</a>
====================================
default route with empty path
========================
route parameters
{ path: 'detail/:id', component: HeroDetailComponent }

passing route params in router link


<a [routerLink]="['/hero', hero.id]">
==================================
getting the router parameters and display the values
this.route.snapshot.paramMap.get('id')
this.location.back() to go back to prevo=ious location

paramMap API - has(name), get(name), getAll(name), keys

import { Component, OnInit } from '@angular/core';


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

import { Hero } from '../hero';


import { HeroService } from '../hero.service';

@Component({
selector: 'app-hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls: [ './hero-detail.component.css' ]
})
export class HeroDetailComponent implements OnInit {
hero: Hero;

constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) {}

ngOnInit(): void {
this.getHero();
}

getHero(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}

goBack(): void {
this.location.back();
}
}

=====================================================
<base href="/"> in index.html
==========================================
different route paths

const appRoutes: Routes = [


{ path: 'crisis-center', component: CrisisListComponent },
{ path: 'hero/:id', component: HeroDetailComponent },
{
path: 'heroes',
component: HeroListComponent,
data: { title: 'Heroes List' } // stores static data such as page titles,
breadcrumb etc
},
{ path: '',
redirectTo: '/heroes',
pathMatch: 'full'
},
{ path: '**', component: PageNotFoundComponent }
];

=============================================================
order of the path mathes is important
===============================================
routerLinkActive a drectiv used to add css classes to a link basedon it's active

<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>


<a routerLink="/heroes" routerLinkActive="active my-another-css-class">Heroes</a>

here active is a css class


============================================================
routerLinkActiveOptions="{exact:true}" to add the routerLinkActive only hen the
router is exactly matched (in case of parent and child routes)
============================================================
RouterState
After the end of each successful navigation lifecycle, the router builds a tree of
ActivatedRoute objects that make up the current state of the router.

some properties of ActivatedRoute url, data, paramMap, queryParamMap, fragment,


outlet - name of the router-outlet, routeConfig, parent, firstChild, children

===================================================
Router events
NavigationStart, RouteConfigLoadStart, RouteConfigLoadEnd, NavigationEnd etc
===========================================

Summary of different Router parts


Router, RouterModule, Routes, Route, RouterOutlet, RouterLink, RouterLinkActive,
ActivatedRoute, RouterState
=================================================================
child routes

=======================================================

Route guards

CanActivate
CanActivateChild
CanDeactivate
Resolve
CanLoad
===================================================
Lazy loading feature modules
CanLoad guard
===============================================

examle

task -1 : load different routes


wildcard route with 404 page
redirectTo
======================================================
task 2 : seperate Route module for app
=====================================================
task 3: heros component feature,
create heros module and feature routing module
ng generate module heroes/heroes --module app --flat --routing

const heroesRoutes: Routes = [


{ path: 'heroes', component: HeroListComponent },
{ path: 'hero/:id', component: HeroDetailComponent }
];
RouterModule.forChild(heroesRoutes)
remove hero route in app module
and import heros module
first feature modules and then app module
passing route params in router link
<a [routerLink]="['/hero', hero.id]">
===============================================================
child routes config
const crisisCenterRoutes: Routes = [
{
path: 'crisis-center',
component: CrisisCenterComponent,
children: [
{
path: '',
component: CrisisListComponent,
children: [
{
path: ':id',
component: CrisisDetailComponent
},
{
path: '',
component: CrisisCenterHomeComponent
}
]
}
]
}
];

======================================================
routerOutlet names
<router-outlet name="popup"></router-outlet>
{
path: 'compose',
component: ComposeMessageComponent,
outlet: 'popup'
},

===================================================
canactivate guard

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


import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from
'@angular/router';

@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
console.log('AuthGuard#canActivate called');
return true;
}
}

{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard],
}
================================================================
lazy loading of modules

{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(mod => mod.AdminModule),
},

You might also like