Setting Up Angular Routing
Provide an example of using Angular CLI to generate a routing module and configure route paths to different components.
ng generate module app-routing --flat --module=app
Generate a new routing module named 'app-routing' with the Angular CLI. The '--flat' option puts the file in the src/app folder rather than its own folder. '--module=app' tells the CLI to register it in the imports array of the AppModule.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FirstComponent } from './first/first.component';
import { SecondComponent } from './second/second.component';
const routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
{ path: '', redirectTo: '/first-component', pathMatch: 'full' },
{ path: '**', redirectTo: '/first-component' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Create and configure the AppRoutingModule. Import the 'RouterModule' and 'Routes'. Define routes to 'FirstComponent' and 'SecondComponent'. Set up a default route that redirects to 'first-component' and a wildcard route for undefined paths. Finally, import routes into the RouterModule and export the configured RouterModule.
import { AppRoutingModule } from './app-routing.module';
@NgModule({
// ...
imports: [
// ...
AppRoutingModule // Add the AppRoutingModule to the imports array
// ...
],
// ...
})
export class AppModule { }
Update the AppModule to include the AppRoutingModule. Import AppRoutingModule and add it to the imports array of the module metadata.