RouterModule
class
npm Package | @angular/router |
---|---|
Module | import { RouterModule } from '@angular/router'; |
Source | router/src/router_module.ts |
Overview
class RouterModule { constructor(guard: any, router: Router) static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders static forChild(routes: Routes): ModuleWithProviders }
How To Use
RouterModule can be imported multiple times: once per lazily-loaded bundle. Since the router deals with a global shared resource--location, we cannot have more than one router service active.
That is why there are two ways to create the module: RouterModule.forRoot
and RouterModule.forChild
.
-
forRoot
creates a module that contains all the directives, the given routes, and the router service itself. -
forChild
creates a module that contains all the directives and the given routes, but does not include the router service.
When registered at the root, the module should be used as follows
@NgModule({ imports: [RouterModule.forRoot(ROUTES)] }) class MyNgModule {}
For submodules and lazy loaded submodules the module should be used as follows:
@NgModule({ imports: [RouterModule.forChild(ROUTES)] }) class MyNgModule {}
Description
Managing state transitions is one of the hardest parts of building applications. This is especially true on the web, where you also need to ensure that the state is reflected in the URL. In addition, we often want to split applications into multiple bundles and load them on demand. Doing this transparently is not trivial.
The Angular router solves these problems. Using the router, you can declaratively specify application states, manage state transitions while taking care of the URL, and load bundles on demand.
Read this developer guide to get an overview of how the router should be used.
Static Members
static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders
Creates a module with all the router providers and directives. It also optionally sets up an application listener to perform an initial navigation.
Options (see ExtraOptions
):
-
enableTracing
makes the router log all its internal events to the console. -
useHash
enables the location strategy that uses the URL fragment instead of the history API. -
initialNavigation
disables the initial navigation. -
errorHandler
provides a custom error handler. -
preloadingStrategy
configures a preloading strategy (seePreloadAllModules
). -
onSameUrlNavigation
configures how the router handles navigation to the current URL. SeeExtraOptions
for more details.
static forChild(routes: Routes): ModuleWithProviders
Creates a module with all the router directives and a provider registering routes.
Constructor
constructor(guard: any, router: Router)
Annotations
@NgModule({ declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES })
© 2010–2018 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://v5.angular.io/api/router/RouterModule