For most apps, there comes a point where the app requires more than a single page. When that time inevitably comes, routing becomes a big part of the performance story for users.
Note: Learn more about routing in the in-depth guide.
In this activity, you'll learn how to set up and configure your app to use Angular Router.
-
Create an app.routes.ts file
Inside
app.routes.ts, make the following changes:- Import
Routesfrom the@angular/routerpackage. - Export a constant called
routesof typeRoutes, assign it[]as the value.
import {Routes} from '@angular/router';export const routes: Routes = []; - Import
-
Add routing to provider
In
app.config.ts, configure the app to Angular Router with the following steps:- Import the
provideRouterfunction from@angular/router. - Import
routesfrom the./app.routes.ts. - Call the
provideRouterfunction withroutespassed in as an argument in theprovidersarray.
import {ApplicationConfig} from '@angular/core';import {provideRouter} from '@angular/router';import {routes} from './app.routes';export const appConfig: ApplicationConfig = {providers: [provideRouter(routes)],}; - Import the
-
Import
RouterOutletin the componentFinally, to make sure your app is ready to use the Angular Router, you need to tell the app where you expect the router to display the desired content. Accomplish that by using the
RouterOutletdirective from@angular/router.Update the template for
Appby adding<router-outlet />import {RouterOutlet} from '@angular/router';@Component({...template: ` <nav> <a href="/">Home</a> | <a href="/user">User</a> </nav> <router-outlet /> `,imports: [RouterOutlet],})export class App {}
Your app is now set up to use Angular Router. Nice work! 🙌
Keep the momentum going to learn the next step of defining the routes for our app.