Routing
One of the most important things while creating an Angular project is creating routes. Without routes you cannot render any page in the browser.
In this page we will learn how to create routes for our pages.
When creating angular project make sure that you select routing to setup router by default.
Defining Module Routes
routes.ts file will be created automatically,
here we can define our paths for each module.
But when we are working on a large projects, such as
fastkart, number of paths will grow very fast, so we create
a separate file routes.ts in routes folder to
keep our routes more organized.
routes.ts
import { Routes } from "@angular/router";
import { AuthGuard } from "../../core/guard/auth.guard";
export const content: Routes = [
{
path: "",
loadChildren: () =>
import("../../components/themes/themes.routes").then(
(r) => r.themeRoutes,
),
},
{
path: "auth",
loadChildren: () =>
import("../../components/auth/auth.routes").then((r) => r.authRoutes),
canActivateChild: [AuthGuard],
},
{
path: "account",
loadChildren: () =>
import("../../components/account/account.routes").then(
(r) => r.accountRoutes,
),
canActivate: [AuthGuard],
},
{
path: "",
loadChildren: () =>
import("../../components/shop/shop.routes").then((r) => r.shopRoutes),
},
{
path: "",
loadChildren: () =>
import("../../components/blog/blog.routes").then((r) => r.blogRoutes),
},
{
path: "",
loadChildren: () =>
import("../../components/page/page.routes").then((r) => r.pageRoutes),
},
];
We give the path for our module, and in loadChildren function we provide our module.
And then we will import this routes.ts file in our app-routes.ts file.
app-routes.ts
import { Routes } from "@angular/router";
import { ScrollPositionGuard } from "./core/guard/scroll.guard";
import { content } from "./shared/routes/routes";
export const routes: Routes = [
{
path: "",
redirectTo: "",
pathMatch: "full",
},
{
path: "maintenance",
loadComponent: () =>
import("./components/maintenance/maintenance").then((m) => m.Maintenance),
},
{
path: "",
loadComponent: () => import("./layout/layout").then((m) => m.Layout),
children: content,
canActivate: [ScrollPositionGuard],
},
];
Now We are done setting our modules path, but when we create
a component inside a Module then path for those components
are written in module_name-routes.ts file.
Please refer to Our
Create New Page Guide to
see how paths for the components are given.