Setting Up Routes
Now that you understand what routing is, let's set up actual routes in your Angular application. Routes define which component to display for which URL path.
Step 1: Create Components
First, let's create some components to navigate between:
ng g c home
ng g c about
ng g c contact
ng g c not-found
Step 2: Define Routes
Open
app-routing.module.ts and define your routes:import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { NotFoundComponent } from './not-found/not-found.component';
const routes: Routes = [
{ path: '', component: HomeComponent }, // default route
{ path: 'home', component: HomeComponent }, // /home
{ path: 'about', component: AboutComponent }, // /about
{ path: 'contact', component: ContactComponent }, // /contact
{ path: '**', component: NotFoundComponent } // wildcard route (404)
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Understanding Route Configuration
path– The URL path (without slash). Empty string '' means default route.component– The component to display for that path.**– Wildcard path matches any URL not matched above (must be last).
Step 3: Add Router Outlet
In your
app.component.html, add the router outlet where routed components will appear:<nav>
<a href="/home">Home</a> |
<a href="/about">About</a> |
<a href="/contact">Contact</a>
</nav>
<!-- Router outlet - components will be displayed here -->
<router-outlet></router-outlet>
Two Minute Drill
- Routes map URL paths to components.
- Empty path '' is the default route.
- Wildcard '**' catches all unmatched URLs (404 page).
- RouterModule.forRoot(routes) configures routes.
- <router-outlet> is where routed components appear.
Need more clarification?
Drop us an email at career@quipoinfotech.com
