Configure Route in Angular 2

,

Configuring Routes

Base URL Tag

The Base URL tag must be set within the <head> tag of index.html inside src folder:

<base href="/">
In the demos we use a script tag to set the base tag. In a real application it must be set as above.

Route Definition Object

The Routes type is an array of routes that defines the routing for the application. This is where we can set up the expected paths, the components we want to use and what we want our application to understand them as.
Each route can have different attributes; some of the common attributes are:
  • path - URL to be shown in the browser when application is on the specific route
  • component - component to be rendered when the application is on the specific route
  • redirectTo - redirect route if needed; each route can have either component or redirect attribute defined in the route (covered later in this chapter)
  • pathMatch - optional property that defaults to 'prefix'; determines whether to match full URLs or just the beginning. When defining a route with empty path string set pathMatch to 'full', otherwise it will match all paths.
  • children - array of route definitions objects representing the child routes of this route (covered later in this chapter).
To use Routes, create an array of route configurations.
Below is the sample Routes array definition:

const routes: Routes = [
  { path: 'component-one', component: ComponentOne },
  { path: 'component-two', component: ComponentTwo }
]; 

RouterModule

RouterModule.forRoot takes the Routes array as an argument and returns a configured router module. The following sample shows how we import this module in an app.routes.ts file.

app/app.routes.ts

import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: 'component-one', component: ComponentOne },
  { path: 'component-two', component: ComponentTwo }
];

export const routing = RouterModule.forRoot(routes);

We then import our routing configuration in the root of our application.

app/app.module.ts

...
import { routing } from './app.routes';

@NgModule({
  imports: [
    BrowserModule,
    routing
  ],
  declarations: [
    AppComponent,
    ComponentOne,
    ComponentTwo
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {
}



Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.