How to handle Routing in Angular2? What are the main routing components? Explain all related concepts like router-link, router-outlet, @RouteConfig and RouteParams in Angular2.
Angular2 has improved so many features from AngularJs 1.x, Router component is one of them. In order to use routing mechanism, there are few steps as following need to be performed.
Goal: For this section, the goal is that, we have a website with two pages (1) home and (2) About and we have to setup Routing mechanism to route these two pages:
What are the main routing COMPONENTS?
Angular2 provides 3 different components for routing configuration:
- _Routes _is the configuration to describe application’s different routes
- _RouterOutlet _is a “placeholder” component that holds the view for each route
- _RouterLink _is a directive to link to routes
Routes:
Routes is an object to describe the routes of the application. For instance, here is an example for our previously specified goal.
We have configure routes which is an array ofRoute. Each entry of the array is The complete list of possible fields used in this configuration are as following:
- path– url of the route used by the matcher DSL.
- component–name of the target component.
- pathMatch– specifies the matching strategy, example : full.
- redirectTo-url that will replace the current matched segment in case of redirection.
- outlet– name of the outlet used as a placeholder for the component. If there is no outlet it would be placed in <router-outlet>
- canActivate– array of DI tokens used to find CanActivate handlers.
- canActivateChild– array of DI tokens used to find CanActivateChild handlers.
- canDeactivate– array of DI tokens used to find CanDeactivate handlers.
- _data _is additional data provided to the component via ActivatedRoute.
- _resolve _is a map of DI tokens used to look up data resolvers.
- _children _is an array used to define nested routes.
Router Directives
Angular RouterModule has 3 different directives. Such as:
- router-outlet
- router-link
- routerLinkActive
router-outlet:
router-outlet is a component from angular/router library. The router is the placeholder to display views inside <router-outlet> tags. As the routes changes, the view inside the <router-outlet> tags also change accordingly.
router-link:
router-link directive is an alternative of HTML href property. The syntax is as following:
Router Link Active:
The RouterLinkActive directive toggles css classes for active RouterLinks based on the current RouterState. This cascades down through each level in our route tree, so parent and child router links can be active at the same time. To override this behavior, we can bind to the [routerLinkActiveOptions] input binding with the { exact: true } expression. By using { exact: true }, a given RouterLink will only be active if its URL is an exact match to the current URL.