263. Module Introduction
This section introduces and builds up Angular’s built-in routing system. You’ll learn:
-
What routing is and why it’s useful in Angular apps
-
How to configure routes and navigate between them
-
Nested (child) routes for more complex UIs
-
Advanced features like data resolvers and route guards
To follow along, download the provided starter project (an app you built earlier without routing), run
-
npm install
-
npm start
You should then see the existing app in your browser—note that selecting a user doesn’t work yet. Over the course of the section you’ll integrate and configure routing to make navigation (and data loading or access control) work as intended.
264. What Is Routing
Routing in Angular lets a single-page application (one HTML file served by the server) behave like a multi-page site by changing views and the browser’s URL without full reloads. As users navigate, Angular’s built-in client-side router reads and updates the URL, loads the appropriate components, and gives the illusion of separate pages—enabling deep links and shareable routes—while keeping everything in one running application.
|
265. Enabling Routing & Adding a First Route
Here’s a concise summary of the steps for adding and organizing routing in your Angular “starting” project:
-
Current situation
-
You have a single
AppComponent
rendered bybootstrapApplication
. -
You’d like the UI to change based on the URL (e.g. selecting a user updates the address bar and the displayed component).
-
-
Enable the Angular router
-
In
main.ts
, callbootstrapApplication(AppComponent, \{ providers: […]})
with a second argument. -
Inside that providers array, add
provideRouter( routesArray )
(from@angular/router
). -
This sets up the router provider so Angular will render components based on the active URL.
-
-
Define your routes
-
A Route is an object with at least:
-
path: the URL fragment (e.g. “tasks”)
-
component: the Angular component to load (e.g.
TasksComponent
)
-
-
Pass your array of routes to provideRouter.
-
-
Module-based apps
-
If you use an NgModule instead of standalone bootstrapApplication, you do the same thing: add
provideRouter(routes)
to the module’s providers array.
-
-
Organize your routing setup (optional conventions)
-
Create
app.routes.ts
→export const routes: Routes = […]
; -
(Optionally) Create
app.config.ts
→
export const appConfig: ApplicationConfig = { providers: […] };
-
Then in
main.ts
simply importappConfig
and/or routes, keeping your entry file clean.
-
-
Next steps
-
With routing enabled, you can now add more route definitions (child routes, parameters, lazy loads, etc.) to power your application’s navigation.
-
|