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
app-routing.module.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
multikart, 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";
import { Error404Component } from './../../components/page/error404/error404.component';
export const content: Routes = [
{
path: "",
loadChildren: () => import("../../components/themes/themes.module").then((m) => m.ThemesModule)
},
{
path: "auth",
loadChildren: () => import("../../components/auth/auth.module").then((m) => m.AuthModule),
canActivateChild : [AuthGuard]
},
{
path: "account",
loadChildren: () => import("../../components/account/account.module").then((m) => m.AccountModule),
canActivate : [AuthGuard]
},
{
path: "",
loadChildren: () => import("../../components/shop/shop.module").then((m) => m.ShopModule)
},
{
path: "",
loadChildren: () => import("../../components/blog/blog.module").then((m) => m.BlogModule)
},
{
path: "",
loadChildren: () => import("../../components/page/page.module").then((m) => m.PagesModule)
},
{
path: '**',
pathMatch: 'full',
component: Error404Component
}
]
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-routing.module.ts file.
app-routing.module.ts
import { content } from './shared/routes/routes';
const routes: Routes = [
...
{
path: "",
component: LayoutComponent,
children: content,
}
];
@NgModule({
imports: [RouterModule.forRoot(routes, {
initialNavigation: 'enabledBlocking',
})],
exports: [RouterModule]
})
export class AppRoutingModule { }
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-routing.module.ts file. Please
refer to Our
Create New Page Guide to
see how paths for the components are given.