W3cubDocs

/Angular

RouterModule

ngmodule

Adds router directives and providers.

See more...

class RouterModule {
  static forRoot(routes: Route[], config?: ExtraOptions): ModuleWithProviders<RouterModule>
  static forChild(routes: Route[]): ModuleWithProviders<RouterModule>
}

See also

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

Static methods

Creates and configures a module with all the router providers and directives. Optionally sets up an application listener to perform an initial navigation.

static forRoot(routes: Route[], config?: ExtraOptions): ModuleWithProviders<RouterModule>

Parameters
routes Route[]

An array of Route objects that define the navigation paths for the application.

config ExtraOptions

An ExtraOptions configuration object that controls how navigation is performed.

Optional. Default is undefined.

Returns

ModuleWithProviders<RouterModule>: The new router module.

Creates a module with all the router directives and a provider registering routes.

static forChild(routes: Route[]): ModuleWithProviders<RouterModule>

Parameters
routes Route[]
Returns

ModuleWithProviders<RouterModule>

Directives

Name Description
RouterLink

Lets you link to specific routes in your app.

RouterLinkActive

Lets you add a CSS class to an element when the link's route becomes active.

RouterLinkWithHref

Lets you link to specific routes in your app.

RouterOutlet

Acts as a placeholder that Angular dynamically fills based on the current router state.

Usage notes

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 {}

© 2010–2019 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/api/router/RouterModule