Routing in Angular2

Posted By : Shilpa Adlakha | 30-Dec-2016

Routing is used to provide urls to different parts of an application.


for example: if in our app their is a dashboard component and a separate home component then we can set their urls as /dashboard and /home respectively.
The router help us to links the URLs to a component.

The following are main components that are used for routing :

1)Routes -- It describes our application’s routes.
2)RouterOutlet -- It is a placeholder component that shows the route’s content.
3)RouterLink -- It is used to link the routes.

Routes: It is an object which we use in our component that specifies the routes to use.
It is used path to determine the URL and the component we want to route to.

for example,

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent }
];

Path         -->  specifies the URL.
Component  -->  where, we want to route to.
redirectTo  --> it is used to redirect  
    

Providing our Router :

 RouterModule.forRoot() function in NgModule to install it in the application:

NgModule:

@NgModule({
  declarations: [
    RoutesDemoApp,
    HomeComponent,
    LoginComponentComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes) // <-- Here we install Router components,services and routes.
  ],
  bootstrap: [ RoutesDemoApp ],
  providers: [
    provide(LocationStrategy, {useClass: HashLocationStrategy})
  ]
})
class RoutesDemoAppModule {}

// bootstrap our app
platformBrowserDynamic().bootstrapModule(RoutesDemoAppModule)
  .catch((err: any) => console.error(err));
 


RouterOutlet: The RouterOutlet directive specifies our router, to render the content in the view.

For example:
    
@View({
  template: `
  <div>
    Stuff in the outer template here
    <router-outlet></router-outlet>
  </div>
 `
})
 

Then whenever we switch routes, the content will be shown in place of the router-outlet tag.

RouterLink:

RouterLink directive,It is used to navigate between routes.

For example:

@View({
  template: `
  <div>
    <nav>
      <a>Navigation:</a>
      <ul>
        <li><a [router-link]="['home']">Home</a></li>
        <li><a [router-link]="['login']">Login</a></li>
        <li><a [router-link]="['dashboard']">Dashboard</a></li>
      </ul>
    </nav>

    <router-outlet></router-outlet>
  </div>
 `
})


 

About Author

Author Image
Shilpa Adlakha

Shilpa is a bright Wordpress Developer, she has good knowledge of HTML, CSS, PHP and Wordpress.

Request for Proposal

Name is required

Comment is required

Sending message..