Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Setting Up Routing in Angular | Section
Angular Fundamentals

bookSetting Up Routing in Angular

Sveip for å vise menyen

To make everything work, you 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.ts

routes.ts

copy

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.ts

config.ts

copy

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.ts

routes.ts

copy

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.ts

routes.ts

copy

When a user visits the root URL (localhost:4200/), Angular will display the TaskListComponent.

Task details page showing info about a single task:

routes.ts

routes.ts

copy

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!

question mark

In which file are the routes typically defined in an Angular application?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 30

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 1. Kapittel 30
some-alt