Course Content
Introduction to Angular
Introduction to Angular
Setting Up Routing in Angular
We'll be improving our Task Tracker app that we've been working on throughout this course.
To make everything work, we need to tell Angular which URL shows which component. This is called routing. Let's get started!
The Main Routing File
When you create an Angular app using the CLI, you can enable routing right from the start β just answer "Yes" when asked about routing. Angular will then create the necessary files for you (which we already did when we created the app). One of those files is app.routes.ts
.
If you don't have this file for some reason, don't worry β you can create it yourself in the root folder of your project. It should look like this:
routes
import { Routes } from '@angular/router'; export const routes: Routes = [];
This file tells Angular what routes exist in your app and which components to show for each route.
Also, make sure your routes are connected in app.config.ts
like this:
config
import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes) ] };
Without the provideRouter(routes)
line, Angular won't know about your routes, even if they're defined in app.routes.ts
.
Configuring Routes
Now let's add routes for our Task Tracker app. Open app.routes.ts
and write the following code:
routes
export const routes: Routes = [ { path: '', component: TaskListComponent }, { path: 'task/:id', component: TaskDetailsComponent }, ];
This is just an array of routes that we export. Each route is an object with these settings:
path
β the URL path;component
β the component to show when navigating to that path.
In our case, we have two routes:
The main page showing the list of tasks.
routes
{ path: '', component: TaskListComponent }
When a user visits the root URL (localhost:4200/
), Angular will display the TaskListComponent
.
Task details page showing info about a single task:
routes
{ path: 'task/:id', component: TaskDetailsComponent }
Here, :id
is a dynamic parameter. Angular understands that :id
can be any value (like /task/1
, /task/42
, etc.). This value is automatically passed to TaskDetailsComponent
, and you can use it to fetch data for that specific task.
So when a user goes to localhost:4200/task/1
, Angular will show TaskDetailsComponent
with the details for task β1.
Right now, nothing will work yet because we only defined the routes, but we havenβt connected them to our components fully. Let's do that in the next chapter!
Thanks for your feedback!