In Angular, you can create a router by following these steps:
- Import the
RouterModule
from@angular/router
in your module file:
import { RouterModule, Routes } from '@angular/router';
- Define your routes using the
Routes
interface. A route consists of a path and a component. For example:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
- Add the
RouterModule
to the imports array of your module file and pass the routes to theforRoot
method:
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
- Add a
router-outlet
directive to your template file to display the components for the corresponding routes:
<router-outlet></router-outlet>
- Finally, make sure to add the routing module to the
imports
array of your main module file:
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, AppRoutingModule],
bootstrap: [AppComponent]
})
export class AppModule { }
With these steps, you can create a basic routing setup in Angular. You can also use the routerLink
directive to create navigation links and the ActivatedRoute
service to access route parameters.