Angular: Routing and Navigation
April 2, 2020
The Angular Router
interprets a browser URL pattern (route) as an instruction to navigate to a view (component) when the route matches a path you create. Anywhere on your site where a link can be clicked to change the URL in the address bar will be caught by the Angular Router
.
Routes must be set in an Angular module in order for the Router
to detect. It’s typical to place all your routes in a single module, but you can also place routes in any local module if you desire. Unless you really have to, it’s recommended to place all routes in a single module to avoid any unforeseen issues (e.g. when using a wild card, or duplicating routes).
The following shows an example of some routes in an Angular module.
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './components/home/home.component'; import { AboutComponent } from './components/about/about.component'; import { ContactComponent } from './components/contact/contact.component'; import { RegisterComponent } from './components/register/register.component'; import { NotfoundComponent } from './components/notfound/notfound.component'; const routes: Routes = [ {path:'', component: HomeComponent}, {path:'home', component: HomeComponent}, {path:'about', component: AboutComponent}, {path:'contact', component: ContactComponent}, {path:'register', component: RegisterComponent}, {path:'**', component: NotfoundComponent}, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }