Angular Router is a powerful JavaScript router which is built and maintained by the Angular core team. It can be imported from the @angular/router package. Angular routing enables navigation from one view to another view without page reload, because it provides a complete routing library with the possibility to have multiple router outlets, different path or url matching strategies, easy access to route parameters and route guards to protect components from unauthorized access.
Routing & navigation can be easily enable by using below steps-
Add base path to src/index.html
file
<base href="/">
Imports router and add router Configuration in app.module.ts
file.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { DashboardComponent } from './dashboard/dashboard.component';
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'dashboard', component: DashboardComponent }
];
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
DashboardComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes)
],
providers: [],
bootstrap: [
AppComponent
]
})
export class AppModule { }
Add RouterOutlet, which is a directive from the router library that is used like a placeholder for all the component. RouterOutlet it is a spot in the template where the router should display the components for that outlet.
<!-- Routed components will be display here -->
<router-outlet></router-outlet>
Add RouterLink and RouterLinkActive.
<h1>Angular Router</h1>
<nav>
<a routerLink="/homr" routerLinkActive="active">Home</a>
<a routerLink="/about" routerLinkActive="active">About</a>
<a routerLink="/dashboard" routerLinkActive="active">Dashboard</a>
</nav>
<router-outlet></router-outlet>