Routing
An Angular best practice is to load and configure the router in a separate, top-level module that is dedicated to routing and imported by the root AppModule.
Generate RoutingModule
By convention, the module class name is AppRoutingModule and it belongs in the app-routing.module.ts in the src/app folder.
--flat puts the file in src/app instead of its own folder. --module=app tells the CLI to register it in the imports array of the AppModule.
You generally don't declare components in a routing module so you can delete the @NgModule.declarations array and delete CommonModule references too.
Route
Routes tell the router which view to display when a user clicks a link or pastes a URL into the browser address bar.
A typical Angular Route has two properties:
path: a string that matches the URL in the browser address bar.
component: the component that the router should create when navigating to this route.
Default Path
forRoot()
The method is called forRoot()
because you configure the router at the application's root level. The forRoot()
method supplies the service providers and directives needed for routing, and performs the initial navigation based on the current browser URL.
Place <router-outlet>
Open the AppComponent template replace the <app-heroes> element with a <router-outlet> element.
The <router-outlet> tells the router where to display routed views.
src/app/app.component.html (router-outlet)
url Navigator
The routerLink is the selector for the RouterLink directive that turns user clicks into router navigations. It's another of the public directives in the RouterModule.
Location Parameter
In the component the router routes to, /detail/:id , add the following imports:
src/app/hero-detail/hero-detail.component.ts
Inject the ActivatedRoute, HeroService, and Location services into the constructor, saving their values in private fields:
Last updated
Was this helpful?