Angular 2 provides routing capabilities that are important for single page applications. The document discusses the main components of routing in Angular 2, including router-link, router-outlet, and @RouteConfig. It also provides steps to implement routing, such as importing directives, mapping URLs to components, and using router-outlet. An example is provided that demonstrates routing in Angular 2 using router-link, router-outlet, and component classes with @RouteConfig.
2. Angular2 still indevelopmentphase. Routingisimportantpartof any SPA (Single Page Application).
Angular2 provide aneasy way to implementrouting.
Angular 2 supports both location strategies using its classes HashLocationStrategy and
PathLocationStrategy. HashLocationStrategy handle by adding the hash sign to the URL and
pushState() method.
Angular 2 identified by the tags <router-link></router-link>
Angular 2 use HTML5 APIs to programmatically support the Back and Forward buttons and
pushState() check the state of URL. User’s navigations history maintain on client side. If view
already loaded into memory then request not goes to the server.
Today I am giving example of Angular 2 routing using HashLocationStrategy.
First we need to understand the main component of Routing in Angular 2.
router-link – router-link directive is use to declare link into view . Its can contains
optional parameters also.
Example :
<a [router-link]="['/AboutUs']">About Us</a>
router-outlet – Its work as a placeholder for views to render then component. Means
template and templateUrl will be render on that location where you will use router-
outlet directive.
Example :
<router-outlet></router-outlet>
@RouteConfig – We map URLs to components in this section which used inside the
<router-link></router-link>.
Example :
@RouteConfig([
{path: '/', component: HomeComponent, as: 'Home'},
{path: '/aboutus', component: AboutUsComponent, as: 'AboutUs' }
3. {path: '/contactus', component: ContactUsComponent, as: 'ContactUs' }
])
RouteParams – Parameter to a component which rendered by the router.
Steps for use routing in Angular 2
1. Add Angular 2 routing library into your html file https://code.angularjs.org/2.0.0-
alpha.45/router.dev.js
<script src="https://code.angularjs.org/2.0.0-alpha.45/router.dev.js"></script>
2. Import all routing directive and classes from 'angular2/router'
import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS,
LocationStrategy, HashLocationStrategy} from 'angular2/router';
3. Map URLs in @RouteConfig
@RouteConfig([
{path: '/', component: HomeComponent,as:'Home'},
{path: '/aboutus',component:AboutUsComponent,as:'AboutUs' }
{path: '/contactus',component: ContactUsComponent,as:'ContactUs' }
])
4. In main root component use router-outlet where you want render components
<router-outlet></router-outlet>
5. Define router-link for which component you want to show
<router-link></router-link>.
Plnkr - http://plnkr.co/edit/2de7CWiUrRMpl3wJgwbT?p=preview