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 Routes File
app.routes.ts file will be created automatically, here we can define our paths
for
each routes.
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/home/home.routes').then(m => m.home)
},
{
path: 'account',
loadChildren: () => import('../../components/account/account.routes').then(m => m.account),
canActivate : [AuthGuard]
},
{
path: '',
loadChildren: () => import('../../components/blog/blog.routes').then(m => m.blog)
},
{
path: '',
loadChildren: () => import('../../components/shop/shop.routes').then(m => m.shop)
},
{
path: '',
loadChildren: () => import('../../components/page/page.routes').then(m => m.page)
},
{
path: '**',
pathMatch: 'full',
component: Error404Component
}
];
We give the path for our routes, and in loadChildren function we provide our routes.
And then we will import this routes.ts file in our app.routes.ts file.
app.routes.ts
import { Routes } from '@angular/router';
import { LayoutComponent } from './layout/layout.component';
import { content } from './shared/routes/routes';
export const routes: Routes = [
{
path: '',
redirectTo: '',
pathMatch: 'full'
},
{
path: '',
component: LayoutComponent,
children: content
},
];
Now We are done setting our routes path, but when we create a component inside a routes then path
for
those components are written in routes_name.routes.ts file. Please refer to Our
Create New Page Guide to see how paths for the components are
given.