When working with the Angular 2+ Router, the standard approach involves defining routes in the app-routing module.
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutComponent } from './pages/about/about.component';
import { HomeComponent } from './pages/home/home.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', component: HomeComponent},
{ path: '**', pathMatch: 'full', component: HomeComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
The route definitions are defined as JavaScript Objects in the format
{ path: '[path]', component: '[componentName]' }
. However, it is recommended to keep this data separate from the components. (An example of this can be found in a tutorial on Angular.io)
Have you ever wondered why there isn't a "routeDefinition" TypeScript class available? Here's an idea:
route-definition.ts
export class RouteDefinition {
constructor(
public path: string,
public component: string) {}
//Additional constructors can be added if needed
}
Instead of using
{ path: '[path]', component '[component]' }
You could simply use
new Route ('[path]', '[component]')
If no specific reason exists, would it go against best practices to create and utilize this class? While individual freedom exists within projects, aligning with established best practices is generally beneficial."