Angular provides a Router to make it easier to define routes for the web applications and to navigate from one view to another view in the application.
What is routing?
When a user enters a web application or website, routing is their means of navigating throughout the application. To change from one view to another, the user clicks on the available links on a page. The Angular Router enables navigation from one view to the next as users perform application tasks.
The Angular Router is an optional service that presents a particular component view for a given URL. It is not part of the Angular core. It is in its own library package, @angular/router. Import what you need from it as you would from any other Angular package.
import { RouterModule, Routes } from '@angular/router';
A router has no routes until it is configured. Route definitions should be configure the router via the RouterModule.forRoot method, and add the result to the AppModule’s imports array.
const appRoutes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'page/:id', component: PageComponent }, { path: 'pages', component: PageListComponent }, { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ]; @NgModule({ imports: [ RouterModule.forRoot( appRoutes) ], ... }) export class AppModule { }
Router Outlet directive will host the proper component based on the route.
What is Router Outlet?
This is an Angular directive that acts as a placeholder that Angular dynamically fills based on the current router state.
<router-outlet></router-outlet> <!-- Routed views go here -->
What does a router.navigate do?
When we want to route to a component we use router.navigate.
this.router.navigate(['/component_name']);
What does a RouterLink do?
The RouterLink directives on the anchor tags give the router control over those elements.
<a routerLink="/component-path" routerLinkActive="active">Router Link</a>